Javascript jQuery 动态创建 table/tr/td 或 etc 并附加属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2362982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:56:26  来源:igfitidea点击:

jQuery dynamically create table/tr/td or etc and append attributes

javascriptjqueryhtml-tablerefactoring

提问by faya

In an example I am having this structure (small example):

在一个例子中,我有这个结构(小例子):

<table id=example>
<tr class="blah test example"><td>Test1</td><td><a href="url">LINK</a>Test11</td></tr>
<tr class="blah test example"><td>Test2</td><td><a href="url">LINK</a>Test22</td></tr>
<tr class="blah test example"><td>Test3</td><td><a href="url">LINK</a>Test33</td></tr>
</table>

In jQuery I would create it dynamically like:

在 jQuery 中,我会像这样动态创建它:

var test = "<table id=" + someIDVar + ">"
           + "<tr class=" + classOneVar 
+ classTwoVar + classThreeVar + ">"....

and etc etc... (lots of other stuff to write). After I would just append it:

等等等等......(还有很多其他的东西要写)。在我只是附加它之后:

$(".somePlaceInHtml").append(test);

So is there any other way to write such a structure dynamically with jQuery? This is a problem for me because I am having a big structure, not as small as I showed in the example. The main reason is I want to get better readability for myself and other developers who will maintain this code.

那么有没有其他方法可以用 jQuery 动态地编写这样的结构呢?这对我来说是个问题,因为我有一个很大的结构,不像我在示例中显示的那么小。主要原因是我希望自己和其他维护此代码的开发人员具有更好的可读性。

回答by Nick Craver

Here's a simplified example:

这是一个简化的示例:

  $(function() {
    var tbl = $('<table></table>').attr({ id: "bob" });
    var row = $('<tr></tr>').attr({ class: ["class1", "class2", "class3"].join(' ') }).appendTo(tbl);
    $('<td></td>').text("text1").appendTo(row);
    $('<td></td>').text("Test22").prepend($('<a></a>').attr({ href: "#" }).text("LINK")).appendTo(row);        
    tbl.appendTo($(".somePlaceInHtml"));        
  });

Wrap the row portion in a loop, replace with variables and it's at least easier to maintain/read in my opinion, but I'm used to jQuery, so your mileage may vary, just an option.

将行部分包装在一个循环中,用变量替换,在我看来至少更容易维护/阅读,但我已经习惯了 jQuery,所以你的里程可能会有所不同,只是一个选项。

A side note, since this is using .text()everywhere, it helps prevents cross-site scripting attacks within your output as well.

附带说明,由于.text()它无处不在,它也有助于防止输出中的跨站点脚本攻击。

回答by naivists

Can you make a "template" out of your string? If yes, then store it in a "constant" variable (e.g. defined in global scope), containing placeholders for actual variables, like {0}, {1}etc, as you would use it in C#'s string.format()method.

你能用你的字符串制作一个“模板”吗?如果是,那么它存储在一个“常数”变量(例如,在全局范围内定义),含占位符实际变量的,比如{0}{1}等等,因为你会在C#中的使用string.format()方法。

So, you would have code like this:

所以,你会有这样的代码:

var rowTemplate = "<tr><td>{0}</td><td>SomePredefinedText {1}</td></tr>";
var alternateRowTemplate = "<tr><td class='a'>{0}</td><td>SomewhatDifferent {1}</td></tr>";
 ...... somewhere deep in your code
 $("#someElement").append(
        rowTemplate.format("myvalue1", "myvalue2")
       ).append(
        alternateRowTemplate.format("myvalue3", "myvalue4")
       );

You would then use the string.format implementation as per this answer: Equivalent of String.format in jQuery

然后,您将按照此答案使用 string.format 实现:Equivalent of String.format in jQuery

回答by Alex Gyoshev

You could create a StringBuilder, much like the one in C#. Here's a snippet took from Telerik Extensions for ASP.NET MVC:

您可以创建一个 StringBuilder,很像 C# 中的那个。这是来自Telerik Extensions for ASP.NET MVC的片段:

$.stringBuilder = function() {
    this.buffer = [];
};

$.stringBuilder.prototype = {

    cat: function(what) {
        this.buffer.push(what);
        return this;
    },

    string: function() {
        return this.buffer.join('');
    }
};

This way, you can have the following code:

这样,您可以拥有以下代码:

var html = new $.stringBuilder();
for (var i in data)
    html.cat("<tr><td>").cat(i).cat("</td><td></tr>");

$('#element').append(html.string());

The benefit of this approach is that you'll have fast concatenation (array joins perform better under IE6), and you could extend the object with other useful function (say, catIfthat takes a boolean expression, or repthat repeats a given string several times).

这种方法的好处是可以快速连接(数组连接在 IE6 下性能更好),并且可以使用其他有用的函数扩展对象(例如,catIf使用布尔表达式,或者rep多次重复给定的字符串) .

回答by poo

Or you could instead of concatenating strings together so make use of the array.joinfunction.

或者,您可以不将字符串连接在一起,而是使用array.join函数。

    for(var i=0;i<arr.length;i++)
    {
      arr[i] = "<tr>" + sth + "</tr>";       
    }

node.innerHTML = arr.join(''); 

回答by Golak Jena

window.onload = function(){
    var btn = document.createElement("button");
    btn.setAttribute("id", "submit_bttn");
    btn.style.width = 125 + "px";
    btn.style.height = 50 + "px";
    btn.innerHTML = "Submit";
    document.body.appendChild(btn);

    var x = document.getElementById("submit_bttn");
    x.onclick = function(){
        alert("hi");
    }
}