jQuery 动态地将 div 附加到表中的 td
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10266532/
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
append div to td in table dynamically
提问by coder25
var $table = $('<table/>').addClass('commentbox');
$table.append('<tr><td>' + 'Comment Id:'+ '</td></tr>');
var $wrap = $('<div/>').attr('id', 'container');
var $in = $('<input type="button" value="Reply"/>').attr('id', 'reply');
$wrap.append($in);
$table.append(
$('<tr>')
.append($('<td>'),
$('<td>'))
);
$table.append($wrap);
I want the div id container to be added inside td but I am getting html
我希望将 div id 容器添加到 td 中,但我得到了 html
<table>
<tbody>
<tr>
<td>Comment</td>
</tr>
<tr>
<td>
</td><td></td>
</tr>
<tbody>
<div id="container">
<input type="button" value="Reply" id="reply">
</div>
</table>
回答by Ayman Safadi
You need to append the $wrap
object to the <td>
element, not the $table
.
您需要将$wrap
对象附加到<td>
元素,而不是$table
.
Try something like this instead:
试试这样的:
var $table = $('<table/>').addClass('commentbox');
$table.append('<tr><td>' + 'Comment Id:'+ '</td></tr>');
var $wrap = $('<div/>').attr('id', 'container');
var $in = $('<input type="button" value="Reply"/>').attr('id', 'reply');
$wrap.append($in);
$table.append(
$('<tr>').append($('<td>').append($wrap), $('<td>').html('hello'))
);
Demo here: http://jsfiddle.net/umCDP/
演示在这里:http: //jsfiddle.net/umCDP/
回答by Stelian Matei
You could also use directly Javascript to create the HTML:
您也可以直接使用 Javascript 来创建 HTML:
var table = document.createElement("table");
var tbody = document.createElement("tbody");
var tr_comment = document.createElement("tr");
var td_comment = document.createElement("td");
td_comment.appendChild(document.createTextNode("Comment"));
tr_comment.appendChild(td);
tbody.appendChild(tr_comment);
var tr_container = document.createElement("tr");
var td_container = document.createElement("td");
var div_container = document.createElement("div");
div_container.setAttribute("id", "container");
var input = document.createElement("input");
input.setAttribute("type", "button");
input.setAttribute("value", "Reply");
input.setAttribute("id", "reply");
div_container.appendChild(input);
td_container.appendChild(div_container);
tr_container.appendChild(td_container);
tbody.appendChild(tr_container);
table.appendChild(tbody);
Adding elements using Javascript, should improve performance.
使用 Javascript 添加元素应该可以提高性能。
What is the most efficient way to create HTML elements using jQuery?
回答by Thach Mai
You need to append to the $('table tbody'). Example:
您需要附加到 $('table tbody')。例子:
$('table tbody').append($('<tr><td>new row</td></tr>'));