我正在从API接收JSON数据,并正在创建jQuery元素并将其附加到列表中。

如何做到这一点,以便当我单击所创建的HTML元素之一时,可以将该元素的原始JSON数据记录到控制台中?

cards.forEach(function (card) {
    var $newCard = $("<li>" + card.name + "</li>");
    $newCard.click(function () {
        // gives me the HTML, but I don't see the properties of the
        // object it was created from.
        console.log(this);
    });
    cardsContainer.append($newCard);
});


我猜我可以在字符串HTML内添加onclick函数吗?有没有办法通过JavaScript来做到这一点?

最佳答案

只需访问卡,因为它位于函数闭包内部。

cards.forEach(function (card) {
  var $newCard = $("<li>" + card.name + "</li>");
  $newCard.click(function () {
      console.log(this); //will be the LI
      console.log(card); //this will be the card
  });
  cardsContainer.append($newCard);
});

08-18 13:31
查看更多