我正在尝试运行这段代码
$('.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
。
我不太明白这一点。有人可以帮忙吗?
最佳答案
最好通过使用事件委托(delegate)而不是使用 inline-js 来做到这一点,尤其是在包含 jQuery 时。
var elm = $('.post').not('.compose');
elm.on('click', 'a', function(){
addToDeck($('input[name=token]').val()+'\','+ $(this).closest('.post').attr("id"));
return false;
});
现在,您已经绑定(bind)了该事件。现在追加只需追加 <a>
elm.append('<a />', { "class" : "card_mark hover" });
关于javascript - $(this) 在 .append() 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27639241/