jQuery从ajax加载的数据获取元素ID

问题描述:

我使用JQuery从PHP页面加载数据,并且工作正常.现在,我希望当我单击这些已加载元素之一时,警报将显示所选元素的ID.我能怎么做?如果我手动将元素放入div输出"中,则可以使用,但是使用$ .ajax()创建的元素则无法使用. 这是代码.

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

对于动态注入的html,您需要执行以下操作:

You need to do as follows for dynamically injected html:

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

基本上,第一次加载页面时不会出现#output,因此您需要将事件绑定到该页面.

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

因此.on使您可以将事件委托给处理程序.

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

有用的链接:

什么是DOM事件委托?

直接事件和委派事件