.on not working on dynamic html

女生的网名这么多〃 提交于 2020-01-05 03:49:04

问题


I am creating drag and drop thing. When drop happens I create new runtime html and want to bind it event, so I have used following .on

 .on ( "event", "selector", function() {

but its not working. Here is Snippet :

$( "#wrap .dragImages" ).on( "click", "button.edit-new-modal", function() {
    var photoId = $(this).attr('data-username');        
    alert(photoId);
});

.on works before drag and drop. But afterwords nothing happens on clicking "button.edit-new-modal"!! What's wrong? Any solution?


回答1:


try :

$(document.body).on( "click", "button.edit-new-modal", function() {
  var photoId = $(this).attr('data-username');        
  alert(photoId);
});



回答2:


This

$( "#wrap .dragImages" ).on( "click", "button.edit-new-modal", function() {

should be :

$(document).on( "click", "button.edit-new-modal", function() {



回答3:


When you wire up event handlers, they are bound to the existing HTML elements only.

As and when you insert dynamic HTML, you must wire up these handlers again.

In your case, you can wrap the event handler setup in a function like this :

    function wireUpHandlers() {
        $( "#wrap .dragImages" ).on( "click", "button.edit-new-modal", function() {
            var photoId = $(this).attr('data-username');        
            alert(photoId);
        });
    }

Call this method in your document.ready and then call this method again, after you have appened your dynamic HTML to the page




回答4:


This is dynamic generated HTML so it will not work. Try using below code snippet

$(document).on( "click", "button.edit-new-modal", function() {

    var photoId = $(this).attr('data-username');        
    alert(photoId);
});


来源:https://stackoverflow.com/questions/30230712/on-not-working-on-dynamic-html

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