jQuery从ajax加载的数据获取元素ID [英] JQuery get element id from ajax loaded data

查看:1230
本文介绍了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事件委托?

直接事件和委派事件

这篇关于jQuery从ajax加载的数据获取元素ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆