简体   繁体   English

将事件处理程序绑定到动态生成的div的问题

[英]Issue with binding event handler to dynamically generated divs

I have a problem with displaying the id of the clicked div on the screen in an alert window. 我在警告窗口中显示屏幕上单击的div的ID时遇到问题。 I am pretty confident this is because of the order of the controls and event handlers being added to the page, however after trying different ways I am unable to get this to work. 我非常有信心这是因为控件和事件处理程序的顺序被添加到页面中,但是在尝试不同的方法之后我无法使其工作。 Unfortunately I can't post reproducible code due to the div's being created from an ajax get request. 不幸的是,由于从ajax get请求创建div,我无法发布可重现的代码。

$(document).ready(function () {
    $.getJSON('ClientPortal/GetSkills', function (data) {
        var test = 'poo';
        $.each(data, function (data) {
            $('#flipContainer').append("<div class=flip id='" + this.Value + "' value='" + this.Value + "'>" + this.Text + "<//div>");
        })
    })
})

$(document).ready(function () {
    $(".flip").on('click', function () {
        alert($(this).attr("id"));
     })
})

Try this : 尝试这个 :

$(document).ready(function () {
    $("#flipContainer").on("click", ".flip", function () {
        alert($(this).attr("id"));
     })
})

You effectively have to base you click-binding on an element existing when the DOM ready event fires... But with this syntax, you delegate the binding on an existing element but it applies to another element contain in the first one... See the jQuery documentation for on (for line "selector") : http://api.jquery.com/on/#on-events-selector-data-handlereventObject . 当DOM ready事件触发时,你实际上必须以对现有元素进行点击绑定为基础......但是使用这种语法,你可以在现有元素上委托绑定,但它适用于第一个包含的另一个元素... on (用于行“选择器”)的jQuery文档: http//api.jquery.com/on/#on-events-selector-data-handlereventObject

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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