简体   繁体   English

如何将onclick事件添加到动态生成的div中

[英]How to add an onclick event to a dynamic generated div

I have a number of div s in my HTML file that are dynamically generated. 我的HTML文件中有一些动态生成的div When I add the div s, I want to add an onclick event to each div . 当我添加div ,我想为每个div添加一个onclick事件。

Each div has a dynamic id . 每个div都有一个动态id Using id , how can add an onclick handler? 使用id ,如何添加onclick处理程序?

Code that generates div s: 生成div的代码:

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

You can apply the click function to the ID after you append it to the dom. 将附加功能附加到dom后,可以将单击功能应用于ID。 So, after your $(".content-conveyor").append(item); 所以,在$(".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: 编辑:在考虑了更多并考虑@ Nemoden的答案之后,你也可以这样做:

 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. 这将附加单击回调而不必使用ID。

You could use the class name of the div for an event handler on all elements that match that class name. 您可以在与该类名匹配的所有元素上使用div的类名作为事件处理程序。

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

.live() is used to attach handlers to DOM elements that may not yet exist in the DOM. .live()用于将处理程序附加到DOM中可能尚不存在的DOM元素。 After $(".content-conveyor").append($item); $(".content-conveyor").append($item); add following code. 添加以下代码。

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

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

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