在JavaScript中创建元素

时间:2009-07-21 23:33:03

标签: javascript jquery

我有很多创建HTML的JavaScript代码。例如:

function Reply(postId) {
    if (!document.getElementById("reply" + postId)) {
        $("#root" + postId).after("<div id='reply" + postId + "'><textarea cols='70' rows='8' style='margin-bottom: 10px'></textarea><br/><span style='margin-bottom: 30px'><input type='button' value='Submit' /><input type='button' value='Cancel' onclick='$(\"#reply" + postId + "\").remove();'/></span></div>");
    }
}

如何使用jQuery使其更具可读性?在JavaScript中创建新元素的最佳方法是什么?我可以看一个例子吗?

6 个答案:

答案 0 :(得分:1)

标准方法不是创建html然后附加或预先添加它,而是创建dom元素并添加它们。

阅读Tim Scarfe的this wonderful article on innerHTML vs DOM.。它写得非常好,并且有点和反点。

您可以在DOM here.上阅读更多内容以及Gecko DOM Reference.上的大量信息。

很抱歉只有粘贴链接,但要经历很多事情。

如果你想要快速入门。看看the Gecko DOM Reference.的这一部分,他们谈论createElement。这是你正在寻找的神奇方法。

答案 1 :(得分:0)

首先,您需要知道要在哪里附加HTML,在这里您会看到documentation:for“manip”:here

因此,假设您想在ID为“insideme”的DIV中创建一个段落。

$("#insideme").append("<p>I'm adding this</p>");

这是创作,现在假设您要插入现有的DIV:

  。

$( “#insideme”)附加($( “DIV#存在的”));

检查documentation,你会发现用于在之前,之后,里面等添加的每个功能。

希望它对你有所帮助。

答案 2 :(得分:0)

两种方式:

  • 改善该字符串的格式
  • 以编程方式安装事件处理程序

例如:

function Reply(postId) {
    if (!document.getElementById("reply" + postId)) {
        // Generate HTML
        var html = "<div id='reply" + postId + "'>";
        html += "<textarea cols='70' rows='8' style='margin-bottom: 10px'></textarea><br/>";
        html += "<span style='margin-bottom: 30px'>";
        html += "<input type='button' value='Submit' />";
        html += "<input class='cancelButton' type='button' value='Cancel' />";
        html += "</span>";
        html += "</div>";

        // Insert into DOM
        $("#root" + postId).after(html);

        // Install event handlers
        $("#root .cancelButton").bind("click", function() {
            $("#reply" + postId).remove();
        });
    }
}

使用DOM是jQuery特别不鼓励的方法因为它太慢了。

更新:正如Chris所说,将这些样式移到CSS文件中以进一步整理它。

答案 3 :(得分:0)

如果要完全使用jquery函数,请查看以下内容是否有效(我还没有测试过)。 Howerver,我实际上会建议不要这样做,因为我明白直接的HTML字符串解析/渲染比一堆js函数调用要快得多优化。

function Reply(postId) {
  var rid = "reply"+postId;
  if (!$('#'+rid)) {
    $('#root'+postID)
      .append("<div/>").attr('id',rid)
        .append("<textarea/>").attr({'cols',70,'row',8,'style','margin-bottom: 10px'})
        .after("<br/>")
        .after("<span />").attr('style','margin-bottom: 30px');
          .append("<input type='button' value='Submit' />")
          .after("<input type='button' value='Cancel' />")
          .onclick(function(){
             $("#"+rid).remove();
          });
  }
}

答案 4 :(得分:0)

  1. 将样式内容移动到CSS文件中。
  2. 删除onclick事件处理程序,将其替换为JQuery live。
  3. 将elementId包装在变量中。

    $(“。cancelButton”)。live(“click”,function(){$(this).remove();});

    function Reply(postId){     var elementId =“reply”+ postId;     if(!document.getElementById(elementId)){         var element = $(“#”+ elementId).after(“
    ”);     }

    }

答案 5 :(得分:0)

对于这些事情,我总是使用EJS。

http://embeddedjs.com/

从jQuery中删除尖括号。

$( ".cancel" ).live( 'click', function() { $( this ).remove(); });

function reply( postId ) {
    if ( $( "#reply" + postId ).size() == 0 ) {
        var context = { postId: postId };
        $( "#root" + postId ).after(new EJS({ url: '/template.ejs' }).render( context ));
    }
}

将它们放在一个模板中,包含所有尖尖的小朋友。

<div id="reply<%= postId %>">
    <textarea cols="70" rows="8" class="reply_editor"></textarea>
    <br>
    <span class="ok_cancel">
        <input type="button" value="Submit">
        <input type="button" value="Cancel" class="cancel">
    </span>
</div>

内联样式是魔鬼的手工作品。

.reply_editor {
     margin-bottom: 10px
}
.ok_cancel {
    margin-bottom: 30px;
}

为了更加清晰,请不要在HTML中附加处理程序。使用jQuery附加它们。