我有一个卡片列表,它是通过循环访问存储在 Firebase 上的一些 JSON 数据创建的。每张卡片分为两部分:“overviewCardInfo”和“overviewCardOptions”。
我想让它在单击选项部分时调用一个函数(在本例中为 .toggleClass()),在单击信息部分时,该卡片的标题显示在其他地方。
到目前为止,我无法实现任何一种效果:卡片的标题无处可见,toggleClass() 要么影响类为“.overviewCardOptions”的 div,要么影响所有卡片,而不仅仅是单击的卡片。
这就是我从 Firebase 获取的用于生成卡片的 JSON 数组:
[{"name":"Push Ups", "duration":3, "break":3},{"name":"Squats", "duration":3, "break":3},{"name":"Running in Place", "duration":3, "break":3}]
JavaScript(一些 jQuery):
// Compile Routine Overview List.
var obj = JSON.parse(localStorage.exercise); // The JSON shown above
obj.forEach(function(exercise)
{
$("#overviewList").append("<li><div class='overviewCard'><div class='overviewCardInfo'>\n\
<h3>" + exercise.name + "</h3><p>" + exercise.duration + " sec.</p><p id='right'>Break: " + exercise.break + " sec.</p>\n\
</div><div class='overviewCardOptions'><img src='images/thrash.png' width='23' alt='' /></div></div></li>");
});
$(document).on("click", ".overviewCardInfo", function() // Attach event handler to document, as cards are generated after other elements on page.
{
$("#overviewSpecifier").css("display", "block"); // Works fine.
$("#infoP").text($(this).text()); // Shows all text contained in card, of course, how do I target the h3 tag specifically? jQuery API docs not helping me understand atm.
});
$(document).on("click", ".overviewCardOptions", function()
{
$(".overviewCard", this).toggleClass("toDelete"); // Fails.
});
HTML:
<ul id="overviewList"></ul>
<div id="overviewSpecifier">
<p id="infoP"></p>
</div>
最佳答案
将 click()
事件附加到 document
而不是使其成为全局的。
$(document).on("click", ".overviewCardOptions", handleThrashClick);
此外,您的对象(实际上它是一个数组)不应该有引号
var obj = "[ ... ]"
应该是 var obj = [ ... ]
在此处查看演示 >> https://fiddle.jshell.net/9a457qzv/3/
关于javascript - 将不同的功能附加到动态创建的卡片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47074478/