【问题标题】:Attach different functions to dynamically created card将不同的功能附加到动态创建的卡片上
【发布时间】: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


【解决方案1】:

click() 事件附加到document 以使其成为全局事件。

$(document).on("click", ".overviewCardOptions", handleThrashClick);

另外,你的对象(实际上它是一个数组)不应该有引号

var obj = "[ ... ]" 应该是var obj = [ ... ]

在这里查看演示>>https://fiddle.jshell.net/9a457qzv/3/

【讨论】:

  • 我想我在描述我的问题时并不清楚。我已经编辑了我的问题,请再看一下!
  • @Brian - 更新后的小提琴,这就是你想要的吗?
  • 我将您的答案标记为 THE 答案,因为它解决了我的主要问题,但是我不禁注意到您的 handleThrashClick 函数与我的问题相同:它只删除了 thrash 图标的图像,或者点击后的overviewCardOptions div,而不是整个卡片。你知道我怎样才能做到这一点吗?无论如何,感谢您的帮助。
猜你喜欢
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 2018-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多