【问题标题】:unable to create multiple div inside div dynamically无法在 div 内动态创建多个 div
【发布时间】:2012-04-22 16:58:46
【问题描述】:
$.post("../../Handler/Topic.ashx", 
       { commentclob: commentClob, 
         commenttitle: commentTitle,
         topicId: id, 
         Button: buttoname },
       function (data) {
         obj = jQuery.parseJSON(data);
         var $table = $('<table/>').addClass('commentbox');

         $table.append('<tr><td>' + 
                       'Comment Id:' + 
                       obj.CommentId + 
                       '</td></tr>');

        var includeReply = "<input type='button' 
                                   class='btnReply' 
                                   value='Reply' 
                                   id='btnReply-" + obj.CommentId + "' />";


        $("#commentContainer").prepend(
          $('<div/>').attr('id', '#comment-' + obj.CommentId)
                     .append($table)
        );

        //This doesnt work         
        $("#comment-" + obj.CommentId).append(
          $('<div/>').attr('id', '#container-' + obj.CommentId)      
                     .append(includeReply)
        );
});

html

  <div id="commentContainer"></div>

我能够成功地将带有#comment-id 的 div 附加到评论容器,但我无法在 #comment-id 中附加另一个 div。

我试过了

               var str = $("<div>").attr("id", "#container-" + obj.CommentId)
               $(str).append(includeReply);
               $table.append('<tr><td>' + 'CommentDiv:' + str + '</td></tr>');

但它给了

CommentDiv:[对象对象]

【问题讨论】:

  • 您是否在错误/调试控制台中看到任何线索?
  • 是的,这是因为您试图将 DOM 节点与字符串连接起来。它可能是一个 HTML 字符串,但它仍然是一个字符串。示例:worksDoesn't work。我建议创建trtd,就像创建div 一样。然后酌情将它们附加在一起。 That seems to work.
  • 你能告诉我如何动态创建按钮,以便我可以附加到 div
  • 我的建议是使用ejohn.org/blog/javascript-micro-templating易于管理和修改
  • 如何以同样的方式创建 td 和 tr...你能举个例子吗

标签: jquery html dom-manipulation


【解决方案1】:

str 是一个 HTML 对象,因此它可以像这样连接。您必须使用.html() 提取标记,然后将其连接起来。

   var str = $("<div>").attr("id", "#container-" + obj.CommentId)
   $(str).append(includeReply);
   $table.append('<tr><td>' + 'CommentDiv:' + str.html() + '</td></tr>');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多