【发布时间】:2017-11-02 11:44:52
【问题描述】:
我有一个卡片列表,它是通过遍历存储在 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>
【问题讨论】:
-
您到底需要什么?绑定另一个事件处理程序
$(".overviewCardInfo").on("click", function(){ ....... }); -
我想我在描述我的问题时并不清楚。我已经编辑了我的问题,请再看一下!
-
$(this).prev(".overviewCard").toggleClass("toDelete"); -
@Satpal 抱歉,这似乎不起作用。
标签: javascript jquery json loops