Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

javascript - JS Jquery How to select a mouse click Target > parent > .Class

I currently have a table set up where each cell in the body looks like

 `<td><div class="container"> <div class="null"><p>?</p></div><div class="question"><p>${response[j].clues[i].question} </p></div>

I am needing to make just the div.null visible, and when clicked it should be hidden revealing div.question. And so I have a mouse event set up that when the user clicks on a td that contains class null it sets visibility to hidden. However I also need to set the div.question to visible but I can seem to figure out a way to target div.question. Does a way exist similar to what I was trying with...

$(e.target.parentNode.question).css("visibility", "visible")

In the code snippet im working in the handleClick(e) function

Here is my code :

// categories is the main data structure for the app; it looks like this:

//  [
//    { title: "Math",
//      clues: [
//        {question: "2+2", answer: 4, showing: null},
//        {question: "1+1", answer: 2, showing: null}
//        ...
//      ],
//    },
//    { title: "Literature",
//      clues: [
//        {question: "Hamlet Author", answer: "Shakespeare", showing: null},
//        {question: "Bell Jar Author", answer: "Plath", showing: null},
//        ...
//      ],
//    },
//    ...
//  ]


fillTable();
handleClick();
/** Get NUM_CATEGORIES random category from API.
 *
 * Returns array of category ids
 */
var NUM_CATEGORIES = [];
async function getCategoryId() {
  //ADD if cat ID exists in array than run axios get again to randomize
  let response = await axios.get('http://jservice.io/api/random?count=6');

  NUM_CATEGORIES.push(response.data.map(result => ({
    id: result.category.id,
  })))
  //console.log(NUM_CATEGORIES);//returns an array length 6 of id's
  return NUM_CATEGORIES;
}

/** Return object with data about a category:
 *
 *  Returns { title: "Math", clues: clue-array }
 *
 * Where clue-array is:
 *   [
 *      {question: "Hamlet Author", answer: "Shakespeare", showing: null},
 *      {question: "Bell Jar Author", answer: "Plath", showing: null},
 *      ...
 *   ]
 */


async function getCategory(catId) {

  var catData = [];
  catId = [];

  await getCategoryId(); //returns an array of category id's

  Object.values(NUM_CATEGORIES).forEach(val => {
    val.forEach(id => {
      catId.push(Object.values(id))
    });
  });

  for (let i = 0; i < 6; i++) {
    let result = await axios.get(`http://jservice.io/api/category?id=${catId[i]}`);
    catData.push(result.data);

  }

  return catData;
}

/** Fill the HTML table#jeopardy with the categories & cells for questions.
 *
 * - The <thead> should be filled w/a <tr>, and a <td> for each category
 * - The <tbody> should be filled w/NUM_QUESTIONS_PER_CAT (6) <tr>s,
 *   each with a question for each category in a <td>
 *   (initally, just show a "?" where the question/answer would go.)
 */

async function fillTable() {

  getCategory().then(response => {
    var wildCard = 0;
    var $titleData = `<table border="1"> <thead>
            <tr>`;

    //generate category titles 

    for (let i = 0; i < 6; i++) {
      $titleData += `<td class="header" > ${response[i].title}  </td>`;
    }
    $titleData += `</tr> 
            </thead> 
            <tbody>`;
    var $rowData = '';


    for (let i = 0; i < response.length; i++) { //generate 5 rows down

      $rowData += `<tr>`;

      for (let j = 0; j < 6; j++) { //fill 6 cells across
        // if($(rowData).is(':contains($(response[j].clues[i].question)')){//check if duplicate question
        //     wildCard= j
        // }

        $rowData += `<td><div class="container">

                <div class="null"><p>?</p></div>
                <div class="question"><p> ${response[j].clues[i].question} </p></div>
                </div></td>`;
      }
      $rowData += `</tr>`;

    }

    $titleData += $rowData;
    $titleData += `</tbody></table>`;

    console.log(response);
    $('body').append($titleData);
  });

}

/** Handle clicking on a clue: show the question or answer.
 *
 * Uses .showing property on clue to determine what to show:
 * - if currently null, show question & set .showing to "question"
 * - if currently "question", show answer & set .showing to "answer"
 * - if currently "answer", ignore click
 * */

function handleClick(e) {
  $("body").on("click", function(e) {
    if ($(e.target).is(".null")) { //if null show question
      console.log("You clicked on a data cell. Yay!")
      $(e.target).css("visibility", "hidden");
      $(e.target.parentNode.question).css("visibility", "visible")
      //$(".container > .question").css("visibility", "visible");

    }
  })


}

/** Wipe the current Jeopardy board, show the loading spinner,
 * and update the button used to fetch data.
 */

function showLoadingView() {

}

/** Remove the loading spinner and update the button used to fetch data. */

function hideLoadingView() {}

/** Start game:
 *
 * - get random category Ids
 * - get data for each category
 * - create HTML table
 * */

async function setupAndStart() {}

/** On click of start / restart button, set up game. */

// TODO

/** On page load, add event handler for clicking clues */

// TODO
/* some colors you may find useful:
  #115ff4
  #060ce9
  #28a200
  #8d2ab5
  #74119c
*/

tbody>tr>td {
  padding: 0%;
  background-color: #115ff4;
  z-index: -3;
  ;
}

.container {
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: -2;
}

.question,
.null {
  margin: 0;
}

.question {
  visibility: hidden;
  z-index: 1;
  color: aliceblue;
}

.null {
  color: aliceblue;
  position: absolute;
  z-index: 2;
  font-size: 200%;
  padding: 1% 8%;
}
<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Jeopardy</title>
  <link href="https://fonts.googleapis.com/css?family=Copse&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="jeopardy.css">
</head>

<body>

  <script src="https://unpkg.com/jquery"></script>
  <script src="https://unpkg.com/axios/dist/axios.js"></script>
  <script src="https://unpkg.com/lodash"></script>
  <script src="jeopardy.js"></script>

</body>

</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First of all , why not using event delegation , to catch only click on .null divs , to prevent check if current target has null class .

Second thing you , once using event delegation you can , access the .question by using $(this).parent().find('.question'), or in your case $(this).next('.question')

So you code should look like :

function handleClick(e) {
   $("body").on("click", ".null", function(e) {
      
      $(this).css("visibility", "hidden");
      $(this).parent().find(".question").css("visibility", "visible")
      // or $(this).next(".question").css("visibility", "visible")
      
   });
}

Here is a snippet :

$("body").on("click", ".null", function(e) {

  $(this).css("visibility", "hidden");
  $(this).parent().find(".question").css("visibility", "visible")
  // OR $(this).next(".question").css("visibility", "visible")
});
.question {
  visibility: hidden;
}

.container {
  width: 100%;
  margin: 0;
  padding: 5px;
  border: 1px black solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="null">
    <p>?</p>
  </div>
  <div class="question">
    <span> question 1 </span>
  </div>

</div>
<div class="container">
  <div class="null">
    <p> ?</p>
  </div>
  <div class="question">
    <span> question 3 </span>
  </div>

</div>
<div class="container">
  <div class="null">
    <p> ?</p>
  </div>
  <div class="question">
    <span> question 2 </span>
  </div>

</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...