jQuery jquery将新元素插入表格单元格而不删除其他元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17536561/
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
jquery insert new element into table cell without erasing other elements
提问by cssyphus
A table contains several rows, each with four cells.
一个表包含多行,每行有四个单元格。
In a cell with id=tdJane
, I already have two input elements:
在带有 的单元格中id=tdJane
,我已经有两个输入元素:
<table>
<tr>
<td id="tdBob">
<input type="hidden" id="hida" value="some stuff">
<input type="hidden" id="hidb" value="other stuff">
<td>
<td id="tdJane">
<input type="hidden" id="hid1" value="some text">
<input type="hidden" id="hid2" value="other text">
<td>
</tr>
</table>
Into cell #tdJane
, I wish to insert a new hidden input field below #hid2
进入单元格#tdJane
,我想在下面插入一个新的隐藏输入字段#hid2
I tried this:
我试过这个:
$('#tdJane').html('<input type="hidden" id="hid3" value="newest text">')
but that overwrites the existing contents of the cell.
但这会覆盖单元格的现有内容。
How can I do it?
我该怎么做?
回答by PSL
You need to use .append(), .html()
will overwrite the contents.
您需要使用.append(),.html()
将覆盖内容。
$('#tdJane').append('<input type="hidden" id="hid3" value="newest text">');
You can use jquery element constructor for more clarity.
为了更清晰,您可以使用 jquery 元素构造函数。
$('#tdJane').append($('<input/>',{type:'hidden',
id: 'hid3',
value:'newest text'}));
See viewsource in this Demo
请参阅此演示中的视图源
回答by StackSlave
Your HTML has a problem, but you should also use jQuery's .append()
method. Your HTML should look more like:
您的 HTML 有问题,但您也应该使用 jQuery 的.append()
方法。你的 HTML 应该看起来更像:
<table>
<tr>
<td id='tdBob'>
<input type='hidden' id='hida' value='some stuff' />
<input type='hidden' id='hidb' value'other stuff' />
</td>
<td id='tdJane'>
<input type='hidden' id='hid1' value='some text' />
<input type='hidden' id='hid2' value='other text' />
</td>
</tr>
</table>
Your jQuery should look more like:
你的 jQuery 应该看起来更像:
$('tdJane').append("<input type='text' id='hid3' value='newest text' />");