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

2023-09-11 01:26:58 作者:食指指向爱情

我公司拥有一批 DIV 的在我的HTML文件动态生成。当我添加了 DIV S,我想一个的onclick 事件添加到每个 DIV

每个 DIV 具有动态 ID 。使用 ID ,怎么可以添加的onclick 处理?

code,生成 DIV S:

 函数createSlider(RESP){
    $每个(RESP,功能(键,VAL){
        VAR项目=< D​​IV CLASS ='项目'ID =+ val.id +>中;

        项目+ =< H2>中+ val.category +&所述; / H 2>中;
        项目+ =< IMG SRC =+ val.image +ALT =「+ val.title +>中;
        项目+ =< / DIV>中;

        $(内容传送)追加(项目);
    });
}
 

解决方案 jquery动态生成div编号问题

您将其追加到DOM后,您可以应用点击功能的ID。所以,你的 $(内容传送)追加(项目)后; 线,补充一点:

  $('#'+ val.id)。点击(函数(){
//做的东西上点击
});
 

修改想着它更多考虑@ Nemoden的答案后,你也可以做到这一点是这样的:

 函数createSlider(RESP){
    $每个(RESP,功能(键,VAL){
        VAR项目=< D​​IV CLASS ='项目'ID =+ val.id +>中;

        项目+ =< H2>中+ val.category +&所述; / H 2>中;
        项目+ =< IMG SRC =+ val.image +ALT =「+ val.title +>中;
        项目+ =< / DIV>中;
        变量$项目= $(项目)。点击(函数(){
            //添加上单击code在这里
        });
        $(内容传送)追加($项目);
    });
}
 

此将附加点击回调而不必使用ID在所有

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

解决方案

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.