Bootstrap, jQuery in modal doesn't work

情到浓时终转凉″ 提交于 2019-12-11 14:56:27

问题


Im making a page where you can check a few lines in a table, and then export them.

Here is the code http://www.bootply.com/Hrll6yz0c1

Code for adding lines to modal export menu works great, but code that deletes lines inside modal doesn't work.

Code for deleting

$('button#delB').click(function() {
     $(this).parent().parent().remove();
});

For this generated table

$('button#addB').click(function() {
                        var toAdd = $(this).parent().parent().find("#sub_id").html();
                        var toAdd2 = $(this).parent().parent().find("#val1").html();   
                        var toAdd3 = $(this).parent().parent().find("#val2").html(); 
                        $('#tblGrid').append("<tr><td>"+toAdd+"</td><td>"+toAdd2+"</td><td>"+toAdd3+"</td><td><button type='button' class='btn btn-default glyphicon glyphicon glyphicon-remove' id='delB'></button></td></tr>"); 

 });

I tried deleting outside modal with the same code and it's working.


回答1:


As I suspected, delB elements are dynamically generated. So they do not exist at the point at which you're attempting to bind the click event handler to them. on() is therefore more suited to what you're trying to do:

$(document).on('click','button#delB',function() {                      
   $(this).parent().parent().remove();
});

http://api.jquery.com/on/

NOTE: It's very likely $(document) is an unnecessary scope to call on() on, make it more specific depending on your context.

As an aside: heed the advice of George, make sure your ids are all unique or you'll run into problems.



来源:https://stackoverflow.com/questions/27146258/bootstrap-jquery-in-modal-doesnt-work

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