$(this) 在 .append() 中不起作用

$(this) not working within .append()

本文关键字:不起作用 append this      更新时间:2023-09-26

我正在尝试运行这段代码

$('.post').not('.compose').append('<a class = "card_mark hover" onclick = "addToDeck('''+$('input[name=token]').val()+''','+$(this).attr("id")+');return false"></a>');

但是$(this).attr("id");正在undefined回归.

我不太清楚这一点。谁能帮忙?

最好

使用事件委托而不是使用内联 js 来执行此操作,尤其是在包含 jQuery 时。

var elm = $('.post').not('.compose');
elm.on('click', 'a', function(){
   addToDeck($('input[name=token]').val()+''','+ $(this).closest('.post').attr("id"));
   return false;
});

现在,您已经绑定了事件。现在附加只需附加<a>

elm.append('<a />', { "class" : "card_mark hover" });

为了演示如何保持与现在相同的结构,您可以使用 each 循环,以便您可以隔离$('.post')的实例,以便使用它来帮助创建 html 并this成为您希望的那样。

$('.post').not('.compose').each(function(){
   /* now "this" is the individual element with class=post */
   $(this).append('<a class = "card_mark hover" onclick = "addToDeck('''+$('input[name=token]').val()+''','+$(this).attr("id")+');return false"></a>');
});