JQuery get element id from ajax loaded data

巧了我就是萌 提交于 2019-12-13 01:15:28

问题


I load data from a PHP page with JQuery and it works fine. Now I want that when I click on one of these loaded elements an alert shows the id of the selected element. How can I do? If I put an element manually into the div "output" it works, but with the element created with $.ajax() it doesn't works. Here is the code.

<input type="text" id="ricerca">
<div id="output" style="border: 1px solid #FF0000;"></div>
$(document).ready(function () {
    // Autocomplete
    $("#ricerca").keyup(function () {
        $(function () {
            var ricerca = $("#ricerca").val();
            $('#output').html("");
            if (ricerca.length > 0) {
                $.ajax({
                    url: 'dati.php',
                    method: 'POST',
                    data: {
                        ricerca: ricerca
                    },
                    dataType: 'json',
                    success: function (data) {
                        for (var i in data) {
                            var row = data[i];
                            var id = row[0];
                            var name = row[1];
                            $('#output').append("<a id='" + id + "' href='#'>" + name + "</a><br>");
                        }
                    }
                });
            }
        });
    });

    // Show ID
    $('#output a').click(function () {
        alert(this.id);
    });
});

回答1:


You need to do as follows for dynamically injected html:

$(document).on("click", "#output a", function() {
    alert(this.id);
});

Basically #output wont be there when you first load the page and hence you will need to bind the event to it.

So .on enables you to delegate the event to the handler.

Helpful links:

What is DOM Event delegation?

Direct and delegated events




回答2:


You have to use .on() for registering click event of dynamically generated element

// Show ID

    $(document).on("click",'#output a',function() {
         alert(this.id);
    });



回答3:


It should be

alert($(this).attr("id"));


来源:https://stackoverflow.com/questions/29279034/jquery-get-element-id-from-ajax-loaded-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!