我有一个简单的代码,有2个div。 一个div包含一个名为“add”的按钮。 单击它时,将在第二个div中添加其他按钮。 当您单击第二个div中的任何按钮时,它会自行删除。 正如您在下面的代码中看到的,我使用append在第二个div中添加按钮。 这就是我的问题所在。 如果删除按钮已经在div中,则代码有效。 (意味着它在点击时会删除)。 但是附加的按钮不会删除自己。 单击时如何使附加按钮自行删除?
<title>AutoSuggestion using Ajax, Jquery and PHP</title> <script src="js/jquery-1.11.1.min.js" ></script> <script type="text/javascript"> $(document).ready(function(){ $('#add').click(function(){ var return_value = "appended button (click to delete me)"; $('.seconddiv').append('<button class ="remove">'+return_value+'</button>'); }); $( '.remove' ).click(function() { $( this ).remove(); }); }); </script> <div class="firstdiv"><button id ="add" >add</button></div> <div class="seconddiv"><button class ="remove" >click to delete me</button></div>i have a simple code that has 2 divs. one div consists one button called "add". When its clicked, that will add other button in the second div . When you click any button in the 2nd div, it suppose to delete itself. as you can see in the code below, i am adding buttons in the second div using append. That's where my question comes. The code works if the delete button is already in the div. (meaning it will delete when its clicked). However buttons that are appended dont delete themselves. How do i make the buttons appended to delete themselves when clicked?
<title>AutoSuggestion using Ajax, Jquery and PHP</title> <script src="js/jquery-1.11.1.min.js" ></script> <script type="text/javascript"> $(document).ready(function(){ $('#add').click(function(){ var return_value = "appended button (click to delete me)"; $('.seconddiv').append('<button class ="remove">'+return_value+'</button>'); }); $( '.remove' ).click(function() { $( this ).remove(); }); }); </script>
<div class="firstdiv"><button id ="add" >add</button></div> <div class="seconddiv"><button class ="remove" >click to delete me</button></div>
最满意答案
这是重新绑定的问题
http://jsfiddle.net/87pt31La/
$(document).ready(function(){ //intial call on load bindFunc() $('#add').click(function(){ var return_value = "appended button (click to delete me)"; $('.seconddiv').append('<button class ="remove">'+return_value+'</button>'); bindFunc() }); //any Js code that needs to be rebinded function bindFunc(){ $( '.remove' ).click(function() { $( this ).remove(); }); } });当你添加新的HTML时,它没有绑定到JS,所以你必须重新绑定它。
This is a rebinding issue
http://jsfiddle.net/87pt31La/
$(document).ready(function(){ //intial call on load bindFunc() $('#add').click(function(){ var return_value = "appended button (click to delete me)"; $('.seconddiv').append('<button class ="remove">'+return_value+'</button>'); bindFunc() }); //any Js code that needs to be rebinded function bindFunc(){ $( '.remove' ).click(function() { $( this ).remove(); }); } });When you add new html it isn't binded to the JS, so you have to rebind it.
更多推荐
发布评论