我正在尝试通过在同一表格的 tfoot
中添加文本框字段的值来构建表格。最终目标是能够内联编辑之前添加的行,同时仍然保留添加更多行的能力。
我有以下标记:
<table>
<thead>
<tr>
<th>Service</th>
<th>Protocol</th>
<th>Source Port</th>
<th>Destination Port</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<td>
<input type="text" data-function="service" value="foo" />
</td>
<td>
<input type="text" data-function="protocol" value="bar" />
</td>
<td>
<input type="text" data-function="sourcePort" value="baz" />
</td>
<td>
<input type="text" data-function="destPort" value="fob" />
</td>
<td>
<button id="addBtn" type="button">Add</button>
</td>
</tr>
</tfoot>
</table>
下面的脚本将 tfoot
中的所有 input[type=text]
元素存储在 inputs 变量中。从那里我尝试使用 .index()
来识别然后检索每个文本框的值:
$(document).ready(function () {
$('#addBtn').click(function (e) {
var inputs = $(this).closest('tfoot').find('input[type=text]');
console.log(inputs);
var serviceIndex = inputs.index('[data-function="service"]');
console.log(serviceIndex);
console.log(inputs[serviceIndex].value);
// the remaining indexes all return -1
var protocolIndex = inputs.index('[data-function="protocol"]');
console.log(protocolIndex);
console.log(inputs[protocolIndex].value);
var sourcePortIndex = inputs.index('[data-function="sourcePort"]');
console.log(sourcePortIndex);
console.log(inputs[sourcePortIndex].value);
var destPortIndex = inputs.index('[data-function="destPort"]');
console.log(destPortIndex);
console.log(inputs[destPortIndex].value);
});
});
不幸的是,选择器 data-function="X"
选择器仅适用于服务。所有其他选择器都返回 -1
表示未找到值。以上代码来自这个jsFiddle which illustrates the problem .我不习惯使用索引,但不能使用元素的 id
因为我需要一个更通用的解决方案。
为什么 jQuery .index()当指定选择器时,方法仅适用于集合中的第一个元素?
最佳答案
来自文档:
If .index() is called on a collection of elements and a DOM element or jQuery object is passed in, .index() returns an integer indicating the position of the passed element relative to the original collection.
所以这应该可行:
inputs.index($('[data-function="protocol"]'));
...
关于javascript - 指定选择器时,为什么 jQuery .index() 方法仅适用于集合中的第一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14972173/