3

同じテーブルのテキスト ボックス フィールドから値を追加して、テーブルを作成しようとしてい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>

The below script stores all of the input[type=text] elements in the tfoot in an inputs variable. From there I am trying to use .index() to identify and then retrieve the value of each textbox:

$(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);
    });
});

Unfortunately the selector data-function="X" selector only works for service. All of the other selectors return -1 indicating that a value was not found. The above code is from this jsFiddle which illustrates the problem. I am not wedded to using index, but cannot use the element's id as I need a more general solution.

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

4

2 に答える 2

1

ドキュメントから:

要素のコレクションに対して .index() が呼び出され、DOM 要素または jQuery オブジェクトが渡された場合、.index() は、元のコレクションに対する渡された要素の位置を示す整数を返します。

したがって、これは機能するはずです:

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

デモ: http://jsfiddle.net/Dfxy9/2/

于 2013-02-20T04:24:08.750 に答える
0

使用しているコンテキストでは、jQuery コレクションの最初の.index要素でのみ呼び出されます。jQuery は、非反復メソッド ( 、、 など)に対してこれを行います。これも例外ではありません。.html.attr.text.index

コレクションを使用する代わりに、セレクターを使用してください: http://jsfiddle.net/4kLqb/

于 2013-02-20T04:25:33.257 に答える