简体   繁体   中英

Dynamically created elements all return the same index

I'm dynamically creating dropdowns in a table, and I'm trying to grab the index of the dropdown that triggered the event, like so:

$(".template").on('change', '.dataTypes', function () {
    var selectedDatatype = $(this).find(":selected").val();
    var ix = $(this).index(); // get this index

    $.ajax({
        type: "GET",
        url: "http://localhost...",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            populateListDropdown("gs", ix, result.Result);
        },
        error: function () { },
        timeout: 120000
    });
});

This code, regardless of the dropdown I interact with always returns a 0 for the index and I'm not sure why.

HTML if it's helpful. The page has a single row loaded at startup, and additional are added via button click.

<table class="tblColumns">
    <tr>
        <td>
            <div class="column">
                Select DataType :
                <select class="dataTypes"></select>
        </td>
    </tr>
</table>

index() method returns index based on its siblings. Your all dropdowns are in seperate td . So all have same index.

You are looking for tr index not select . Try

$(this).closest('tr').index();

For further reading, check out https://api.jquery.com/index/

"If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements."

In your HTML the is the only element, hence always returning '0'.

As @Azim pointed out, if you use , it might work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM