简体   繁体   中英

How to handle div image click event for every time execution of div

function first(Objs) {
    var imgid= Objs;
    secondMethod(imgid);
    $('#imags_'+imgid.id).one('click', function(e) {
        alert(imgid.id)
    });    
}

function secondmethod(imgid) {
    var boxText = document.createElement("div");
    boxText.id="imags_"+imgid.id;
    boxText.innerHTML = '<div id="content" >' + '<img src=\"image.png\" width=\"50px\" height=\"50px\" id ="\images_id\" />' + '</div>';         
}
  • I refreshing(executing) first method every 10 seconds( Objs.id=1 ) .
  • So its two methods executed every 10 secs,
  • Example after 3 refreshes(ie 3 times executes), then when I click image I got 3 time imageid(ie alert output is 1).
  • how to get only one output when i clicked image with last executed object id.
  • please help me from this problem.

Give the image a class:

boxText.innerHTML = '<div id="content" >'+        
    '<img src=\"image.png\" width=\"50px\" height=\"50px\" class ="\images_id\" />'+
    '</div>';

And use a delegated event:

$(document).on('click', '.images_id', function() {
    alert(this.id)
});

Also, your example doesn't show it but I assume boxText is appended to the DOM at some point?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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