我正在try 在点击时显示/隐藏更多关于姓名的信息,但不知道如何让它只需点击一次就能工作.
我正在获取包含游戏相关信息的JSON,并使用JS创建一个div,如下所示:
fetch("thething.json")
.then(res => res.json())
.then(data =>{
games = data.map(game => {
const newDiv = document.createElement("div");
newDiv.className = "game-info";
newDiv.innerHTML = `
<p onclick="toggler()";>${game.Name}</p>
<div class="info">
<img src="${game.Thumbnail}">
<p>${game.Description}</p>
</div>
`;
document.body.appendChild(newDiv);
return {name: game.Name, element: newDiv}
JSON本身就有一大堆关于游戏的信息, struct 如下:
[{"Name: "gamename1",
"Thumbnail: "https://imglocation",
"Description": "This game is indeed a game"
},
{"Name: "gamename2",
"Thumbnail: "https://imglocation2",
"Description": "This game2 is indeed a game2"
}
]
Toggler函数的编写方式如下:
function toggler(){
$('div.game-info').click(function(e){
$(this).children('.info').toggle();
});
}
它有点工作,但它需要一个或多个点击来查看额外的信息.我知道这个问题是由于多个onClick调用,但不知道如何使它与一个单一的点击.我试着使用jQuery而不使用toggler函数,但是它打开了所有名字的信息,而不仅仅是被点击的那个名字.所以,如果有人可以告诉我如何摆脱次要点击或如何正确地定位我点击innerHTML部分的信息,那将是伟大的!
找到答案了.快速跟进问题.我,使用这个设置来查找游戏,但它不会与新代码工作,所以有一种方法使用, "return {name:game. Name,element:newDiv}"来自JQuerry中的上一个版本?
searchInput.addEventListener("input", e=>{
const value = e.target.value.toLowerCase()
games.forEach(game =>{
const isVisible = game.Name.toLowerCase().includes(value)
game.element.classList.toggle("hide", !isVisible)
});
})
快速搜索找到答案,如果有人偶然发现在future .seachInput抓取input ="search",然后隐藏不匹配的内容:
const searchInput = document.querySelector("[data-search]")
$(searchInput).on("keyup", function(){
let value = $(this).val().toLowerCase();
$(".toggle-info").filter(function(){
$(this).toggle($(this).text().toLowerCase().indexOf(value) >
-1)
});
});