我在记录器中用PHP钻了一张桌子。我正在使用该表来更新定价。我有一个文本输入和一个表单按钮。该按钮触发Ajax调用并更新表。现在我在重复区域内有jQuery脚本,但有时我有超过500条记录..现在我使用btn_2345,其中2345是唯一的我和脚本点击btn_2345。如何只在重复之外使用脚本一次,并获取输入文本框和唯一ID的值。
答案 0 :(得分:3)
如果您有这样的表:
<table>
<tr>
<td><input type="text"></td>
<td><button>go</button></td>
</tr>
<tr>
<td><input type="text"></td>
<td><button>go</button></td>
</tr>
<!-- ... -->
</table>
然后,您可以向行添加data-id
属性,从<button>
向<tr>
向上移动DOM以获取ID,然后返回DOM查找<input>
。 HTML有点像这样:
<table>
<tr data-id="11">
<td><input type="text"></td>
<td><button>go</button></td>
</tr>
<tr data-id="23">
<td><input type="text"></td>
<td><button>go</button></td>
</tr>
<!-- ... -->
</table>
JavaScript类似这样:
$('table button').click(function() {
var $tr = $(this).closest('tr');
var id = $tr.data('id');
var val = $tr.find('input[type=text]').val();
// ...
});
如果您愿意,也可以将点击处理程序放在命名函数中。
您可以通过将一个类附加到<tr>
元素并将该类与closest
一起使用来使其更好:
<table>
<tr data-id="11" class="one-chunk">
<td><input type="text"></td>
<!--...-->
和
$('table button').click(function() {
var $chunk = $(this).closest('one-chunk');
var id = $chunk.data('id');
var val = $chunk.find('input[type=text]').val();
//...
});
答案 1 :(得分:0)
为什么不使用
<input type="submit" class="my-button" id="2345">
然后你可以在jquery中使用class作为选择器,并使用id作为你需要的值。
答案 2 :(得分:0)
如果您为许多行生成HTML,其中每行都有一个与之关联的按钮,为什么不在每次迭代时使用onClick
和rowId
进行生成:
onClick="javascript: edit( rowId );"
因此生成的结果如下所示:
<table>
<tr>
<td><input type="text"></td>
<td><button onclick="javascript: edit( '2345' );">edit</button></td>
</tr>
<tr>
<td><input type="text"></td>
<td><button onclick="javascript: edit( '2346' );">edit</button></td>
</tr>
....
</table>
您无需猜测ID。