javascript - .append jQuery 函数

标签 javascript jquery jquery-events

操作后应生成的 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/

相关文章:

jQuery - 公开事件

javascript - jquery劫持是否可能

php - 使用 JQuery 表单中的值来选择与表单值匹配的数据库项目

javascript - 像媒体屏幕一样工作的 jquery 代码

javascript - 当服务器变量更改值时,如何触发 jquery 的更改?

javascript - jquery点击事件不会触发

php - Internet Explorer jQuery 重定向

javascript - jQuery 函数使用 href 而不是 input?

JavaScript onClick 隐藏和显示

javascript - C 中 Websocket 服务器的问题