让我先解释为什么我需要这样做才有意义。在页面上有各种部分的标签/标题。用户可能希望将这些标题命名为其他标题或使用其他语言。而不是" Color"也许" Hue"。有一个表格包含标签和部分信息的信息。所以,"颜色"和"红色"等等。
当用户更改表格中的标签输入字段并单击保存时,我需要的是 - 要更改页面上的相应标签。在表中,第一列是匹配标签的id,也是相应输入的类。 http://jsfiddle.net/NNpCB/4/
的jQuery
// dynamically give table text inputs, with correct label classes
var valueCol = $("table#ruleTable tr td:nth-child(2)");
valueCol.html(function(){
return '<input value="' + $(this).text() + '" class="' + $(this).prev().text() + '" />';
});
// save new label text
$('.saveLbl').click(function () {
// for each input that was changed, find the corresponding label(s) and change the label text
// the input .class matches the label #id
});
HTML
<label id="lblcolor">Colors</label>
<ul>
<li>Red</li>
<li>Blue</li>
<li>Yellow</li>
</ul>
<label id="lblshape">Shapes</label>
<ul>
<li>Square</li>
<li>Circle</li>
<li>Rectangle</li>
</ul>
<br /><br />
<table id="ruleTable" border='1' cellpadding='15'>
<thead>
<tr>
<th>Label</th>
<th>Display Value</th>
<th>Language</th>
</tr>
</thead>
<tbody>
<tr>
<td>lblcolor</td>
<td>Colors</td>
<td>ENG</td>
</tr>
<tr>
<td>lblshape</td>
<td>Shapes</td>
<td>ENG</td>
</tr>
</tbody>
</table>
<br /><br />
<button class='saveLbl'>Save</button>
答案 0 :(得分:1)
请尝试以下代码:(http://jsfiddle.net/W4k7W/)
$('.saveLbl').click(function () {
// for each input that was changed, find the corresponding label and change the label text
// the input .class matches the label #id
var rows=$("#ruleTable tbody").children();
for(var i=0;i<rows.length;i++){
var rowKids = $(rows[i]).children();
var labelClass=$(rowKids[0]).text();
var value=$($(rowKids[1]).children()[0]).val(); // <--- rowKids[1] is the td , its first child is the input row
$("#"+labelClass).text(value);
}
});