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

标签 javascript jquery indexing

我正在尝试通过在同一表格的 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"]'));
...

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

关于javascript - 指定选择器时,为什么 jQuery .index() 方法仅适用于集合中的第一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14972173/

相关文章:

javascript - 列出开放有限有向图中给定节点的所有可能路径

javascript - 如何使用 Angular js 上传图片?或者如何在输入类型文件中使用/模拟 ng-model?

javascript - return false 在 javascript 对象中不起作用

python - 使用 NumPy 在索引处设置值的更简洁方法

C# 字符串中字符的第三个索引

javascript - TinyMCE 如何将 baseURL 附加到 LINK 和图像的基本路径

javascript - 使用 Javascript 强制网页过期

javascript - 验证动态单选按钮 jQuery

javascript - 使一个类可与其他同名类排序,前提是它们是 w/jquery 的兄弟类

java - 如何使用 Mongo Java 驱动程序编写带有索引交集的查询