我有一个“网格”,每行有几个输入字段。假设每个输入字段代表一周中的一天。
html:
<table id="grid">
<tr>
<td><input class="fri" type="text" value="foo" /></td>
<td><input class="mon" type="text" value="bar" /></td>
<td><input class="tue" type="text" value="baz" /></td>
<td><input class="wed" type="text" value="x" /></td>
<td><input class="thu" type="text" value="y" /></td>
</tr>
...
jQuery:
$('#grid').on('change', '.fri', function () {
var value = $(this).val();
//do something
});
$('#grid').on('change', '.mon', function () {
var value = $(this).val();
//do something
});
// And so on...
可以有任意数量的行,所有行都具有相同的字段。
我做了一个工作 fiddle我正在尝试做的事情。
但是,我觉得我(使用 jQuery)重复得太多了,我想知道是否有一种方法可以更简洁地完成上述操作(最好使用 jQuery)。
最佳答案
您可以使用元素选择器而不是使用单独的 ID 然后绑定(bind)它们:
$('#grid').on('change', 'input:text', function () {
var value = $(this).val();
//do something
});
此外,如果您在同一个表格中有其他不想定位的文本框,则使用多类选择器:
$('#grid').on('change', '.fri,.mon,.tue', function () {
var value = $(this).val();
//do something
});
关于javascript - 每行具有多个输入字段的网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28709716/