我有一个包含大量数据的表,由于某种原因,每次<td> </td>
后input
的索引不断重置。为此,我创建了这个函数
$('.custom-input').each(function(index) {
$(this).attr('data-index', index);
});
但是当我尝试使用它时,在"更改功能"上,它不起作用。
我当前的代码:
$('.custom-input').each(function(index) {
$(this).attr('data-index', index);
});
$('.custom-input[data-index=" '+index+' "]').on('change', function() {
alert($(this).index());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
<td>
<input class="custom-input" type="text" value="0">
<input class="custom-input" type="text" value="0">
<input class="custom-input" type="text" value="0">
</td>
<td>
<!-- The index for the next input should not be reset -->
<input class="custom-input" type="text" value="0">
<input class="custom-input" type="text" value="0">
<input class="custom-input" type="text" value="0">
</td>
</tr>
change 事件不起作用,因为您尝试使用不存在的索引变量将其附加到每个特定元素。我不知道你正在做什么的目的是什么,但你应该将事件附加到所有.custom-input
元素上。另外,我建议使用input
事件而不是change
。
当
<input>
的值 、<select>
或<textarea>
元素已更改。更改事件针对
<input>
、<select>
和<textarea>
触发 元素,当 用户。与输入事件不同,更改事件不一定 每次更改元素值时触发。
$('.custom-input').each(function(index) {
$(this).attr('data-index', index);
console.log("data-index set to: " + $(this).attr('data-index'));
});
$('.custom-input').on('input', function() {
alert($(this).index());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr>
<td>
<input class="custom-input" type="text" value="0">
<input class="custom-input" type="text" value="0">
<input class="custom-input" type="text" value="0">
</td>
<td>
<!-- The index for the next input should not be reset -->
<input class="custom-input" type="text" value="0">
<input class="custom-input" type="text" value="0">
<input class="custom-input" type="text" value="0">
</td>
</tr>
你不应该在这个jquery选择器上删除索引周围的空格吗? 像这样:
$('.custom-input[data-index="'+index+'"]').on('change', function() {
alert($(this).index());
});