How to add an onclick event to a dynamic generated div

帅比萌擦擦* 提交于 2019-12-12 12:33:48

问题


I have a number of divs in my HTML file that are dynamically generated. When I add the divs, I want to add an onclick event to each div.

Each div has a dynamic id. Using id, how can add an onclick handler?

Code that generates divs:

function createSlider(resp) {
    $.each(resp, function(key, val) {
        var item = "<div class='item' id="+val.id+">";

        item += "<h2>" + val.category + "</h2>";
        item += "<img src=" + val.image + " alt=" + val.title + ">";
        item += "</div>";

        $(".content-conveyor").append(item);
    });
}

回答1:


You can apply the click function to the ID after you append it to the dom. So, after your $(".content-conveyor").append(item); line, add this:

$('#' + val.id).click(function() {
// Do stuff on click
});


Edit: After thinking about it more and considering @Nemoden's answer, you could also do it like this:
function createSlider(resp) {
    $.each(resp, function(key, val) {
        var item = "<div class='item' id="+val.id+">";

        item += "<h2>" + val.category + "</h2>";
        item += "<img src=" + val.image + " alt=" + val.title + ">";
        item += "</div>";
        var $item = $(item).click(function() {
            // Add on click code here
        });
        $(".content-conveyor").append($item);
    });
}

This would attach the click callback without having to use the ID at all.




回答2:


You could use the class name of the div for an event handler on all elements that match that class name.

$(".item").click(function() {
    //
 });



回答3:


.live() is used to attach handlers to DOM elements that may not yet exist in the DOM. After $(".content-conveyor").append($item); add following code.

 $('#' + val.id).live(click,function() {
 // your code here
 });


来源:https://stackoverflow.com/questions/8365848/how-to-add-an-onclick-event-to-a-dynamic-generated-div

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