我的页面中有一个表格,如下所示;
<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 是 fiddle
最佳答案
我建议如下:
$('#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));
}
});
});
编辑以回应来自@mplungjan的评论(下):
.text(something)
must surely be faster and simpler to read than.text("").append(something)
in any case. And you are not adding text but html so even more reason to use justhtml()
.
当然,他是对的。因此:
$('#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));
}
});
});
引用资料:
关于javascript - 如何将文本更改为文本输入元素 - jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10862476/