我的页面中有一张表格,如下所示;
<table id="tbl" cellpadding="0" cellspacing="0" style="width: 100%">
<tr>
<td class="field1s">field1x</td>
<td class="field2s">field2x</td>
<td class="field3s">field3x</td>
<td class="field4s">field4x</td>
<td class="xx">#</td>
</tr>
</table>
该表包含这么多行。当我单击最后一个单元格 (xx) 时,我希望该行中的所有其他文本更改为<input type="text" />
分别有对应的类,里面有对应的文本。当用户再次单击时xx
,该行可能会使用更改的文本进行更新。
我已经收集了数据并做了一些工作。
Here http://jsfiddle.net/767y4/是小提琴
我建议如下:
$('#tbl').on('click','.xx',function() {
$(this).siblings().each(
function(){
// if the td elements contain any input tag
if ($(this).find('input').length){
// sets the text content of the tag equal to the value of the input
$(this).text($(this).find('input').val());
}
else {
// removes the text, appends an input and sets the value to the text-value
var t = $(this).text();
$(this).html($('<input />',{'value' : t}).val(t));
}
});
});
JS 小提琴演示 http://jsfiddle.net/davidThomas/767y4/8/.
Edited回应评论@mplungjan https://stackoverflow.com/questions/10862476/how-to-change-text-into-text-input-element-jquery/10862581#comment14151231_10862581(以下):
.text(something)
肯定比.text("").append(something)
任何状况之下。而且您不是添加文本而是添加 html,因此更有理由使用html()
.
当然,他是对的。所以:
$('#tbl').on('click','.xx',function() {
$(this).siblings().each(
function(){
if ($(this).find('input').length){
$(this).text($(this).find('input').val());
}
else {
var t = $(this).text();
$(this).html($('<input />',{'value' : t}).val(t));
}
});
});
JS 小提琴演示 http://jsfiddle.net/davidThomas/767y4/11/.
参考:
-
append() http://api.jquery.com/append/.
-
each() http://api.jquery.com/each/.
-
find() http://api.jquery.com/find/.
-
siblings() http://api.jquery.com/siblings/.
-
text() http://api.jquery.com/text/.
-
val() http://api.jquery.com/val/.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)