问题描述
我目前设置了一个表格,其中正文中的每个单元格看起来像
`<td><div class="container"> <div class="null"><p>?</p></div><div class="question"><p>${response[j].clues[i].question} </p></div>
我只需要让 div.null 可见,当点击它时应该隐藏显示 div.question。所以我设置了一个鼠标事件,当用户单击包含类 null 的 td 时,它将可见性设置为隐藏。但是,我还需要将 div.question 设置为可见,但我似乎可以找到一种针对 div.question 的方法。是否存在类似于我尝试使用的方法...
$(e.target.parentNode.question).css("visibility","visible")
这是我的代码:
// 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",// {question: "Bell Jar Author",answer: "Plath",// ...
// ],// ...
// ]
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",* {question: "Bell Jar Author",* ...
* ]
*/
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>
解决方法
首先,为什么不使用事件委托,只捕获.null
div 上的点击,以防止检查当前目标是否为空类。
第二件事,一旦使用事件委托,您就可以使用 .question
访问 $(this).parent().find('.question')
,或者在您的情况下使用 $(this).next('.question')
所以你的代码应该是这样的:
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")
});
}
这是一个片段:
$("body").on("click",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>
您可以使用 .parent() 获取对象(类或 id)的父级
例如 $(e.target).parent() ,这将返回用户点击的项目的父项