当指定了选择器时,为什么jQuery.index()方法只适用于集合中的第一个元素

Why does the jQuery .index() method only work for the first element in the collection, when a selector is specified?

本文关键字:适用于 方法 集合 元素 第一个 index 选择器 jQuery 为什么      更新时间:2023-09-26

我正试图通过添加同一表的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]元素存储在输入变量中。从那里我尝试使用.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,它说明了这个问题。我不习惯使用索引,但不能使用元素的id,因为我需要一个更通用的解决方案。

当指定了选择器时,为什么jQuery.index()方法只适用于集合中的第一个元素?

来自文档:

如果对元素集合和DOM元素调用.index()jQuery对象被传入,.index()返回一个整数,指示传递的元素相对于原始集合的位置。

所以这应该有效:

inputs.index($('[data-function="protocol"]'));
...

演示:http://jsfiddle.net/Dfxy9/2/

在使用它的上下文中,.index仅在jQuery集合中的第一个元素上调用。jQuery对任何非迭代方法(例如.html.attr.text)都是这样做的——.index也不例外。

不要使用集合,而是使用选择器:http://jsfiddle.net/4kLqb/