JQuery从ajax加载的数据中获取元素id

时间:2015-03-26 12:57:48

标签: jquery ajax elements

我使用JQuery从PHP页面加载数据,它工作正常。现在我希望当我点击其中一个加载的元素时,警报会显示所选元素的ID。我能怎么做?如果我将一个元素手动放入div"输出"它有效,但使用$ .ajax()创建的元素它不起作用。 这是代码。

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

3 个答案:

答案 0 :(得分:6)

动态注入html需要执行以下操作:

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

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

因此.on使您能够将事件委托给处理程序。

有用的链接:

What is DOM Event delegation?

Direct and delegated events

答案 1 :(得分:1)

您必须使用.on()来注册动态生成元素的点击事件

// Show ID

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

答案 2 :(得分:-1)

应该是

alert($(this).attr("id"));
相关问题