简体   繁体   中英

dynmaic anchor onclick event is not triggered

i am trying to achieve the same behavior in this fiddle http://jsfiddle.net/CWaHL/1/ but the only difference is my anchor tag is dynamically generated through jquery

my code

   acqIdCounter = grouparr.length;
    $("#attendessbox") .append( "
    <div id='acquiantancebox"+acqIdCounter+"' class='acquaintance'
        style='padding: 1%; float: left; position: relative;'>
        <a href='#' class='deleteAcq' onClick='return false;'>
        <img style='max-width: 100%' src='images/crosserror.png' /></a><span
            style='border: 1px solid #DE4062; width: 100%; border-radius: 4px'>"
            + acquiantancename + "<br />" + acquiantancemob + "
        </span>
    </div>

and on click event

$('a.deleteAcq').on('click',function(e){
 alert("test");
 return false;
});

so issue here, when click on the image 'crosserror.png' my anchor click event is not getting triggered. Thanks for your answers, dont know what i am doing wrong!!

The event delegation syntax of on is different.

$(static-eleemnt).on(event, dynamic-element-selector, function(){})

Try

$(document).on('click','a.deleteAcq',function(e){
    alert("test");
    return false;
});

You need to delegate the event to the parent, so you catch it when it bubbles up from the dynamically created elements.

$('#attendessbox').on('click', 'a.deleteAcq', function(e){
  // Your code
});

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