操作后应生成的 HTML:
<div class="comments_action_207">
<div class="list_item_comments list_item_comments_207">
<div class="comment_separator">text goes here</div>
</div>
</div>
操作前的 HTML:
<div class="comments_action_207"></div>
<div class="list_item_comments list_item_comments_207"><div class="comment_separator">text goes here</div></div>
允许我执行上述操作的 JavaScript 是:
$(function() {
$('.comments_action_207').click(function() {
var num = this.className.split('_').pop();
$('</div>',{'class':'list_item_comments list_item_comments_' + num})
.append('<div class="comment_separator">text goes here</div>')
.appendTo(this);
});
});
我测试了上面的 JavaScript,它工作得很好。但我不明白的是为什么我不必传递 opening div 标签,如下所示。如果我传递一个开始的 div 标签,代码将无法按我的预期工作。
$('<div></div>',{'class':'list_item_comments list_item_comments_' + num}).
如果可以的话请逐行解释一下,这样我更容易理解。
最佳答案
您的<div>
无法正确关闭:
$('<div><div/>'
^
jQuery 接受 <div />
, <div>
和<div></div>
,但没有其他(即没有 HTML 属性):http://api.jquery.com/jQuery/#jQuery2
关于javascript - .append jQuery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12449728/