Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

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

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:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...