2016-08-16 105 views
0

这里我创建动态单选按钮,文本区域和点击事件,但我添加和删除按钮的点击事件不适用于动态创建的按钮。我尝试使用jquery的单击事件,但它不工作作为expecte。如何添加。对jQuery函数在我的情况我试着使用:添加事件动态创建按钮

$("#TextBoxesGroup")‌​.on("click", ".abc", (function() { 
//some script 
}); 

,但是当我点击我创造了它新的动态添加按钮完全不添加另一块

<!DOCTYPE html> 
<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
<script> 
$(document).ready(function(){ 
var counter = 2; 
alert(123); 
$(".abc").click(function() { 
if(counter>10){ 
     alert("Only 10 textboxes allow"); 
     return false; 
} 

var newTextBoxDiv = $(document.createElement('div')) 
    .attr("id", 'TextBoxDiv' + counter); 
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' + 
    '<input type="text" name="textbox' + counter + 
    '" id="textbox' + counter + '" value="" ><br><input type="radio" name="gender' + counter + ' value="male" > Male<input type="radio" name="gender' + counter + ' value="male" > Female<br><textarea id="textbox' + counter + ' rows="4" cols="50"></textarea><input type="button" class="abc" id="addButton' + counter + '" value="Add Button" ><input type="button" id="removeButton' + counter + '" value="Remove Button" >'); 

newTextBoxDiv.appendTo("#TextBoxesGroup"); 


counter++; 
}); 
$("#removeButton").click(function() { 
if(counter==1){ 
     alert("No more textbox to remove"); 
     return false; 
    } 

counter--; 
$("#TextBoxDiv" + counter).remove(); 
}); 
$("#getButtonValue").click(function() { 

var msg = ''; 
for(i=1; i<counter; i++){ 
    msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val(); 
} 
alert(msg); 
}); 
}); 
</script> 
</head> 
<body> 

</head> 
<body> 

<div id='TextBoxesGroup'> 
<div id="TextBoxDiv1"> 
    <label>Textbox #1 : </label><input type='textbox' id='textbox1' > 
    <input type="radio" name="gender" value="male"> Male 
    <input type="radio" name="gender" value="female"> Female<br> 
    <textarea id="textbox" rows="4" cols="50"></textarea> 
    <input type='button' class="abc" value='Add Button' id='addButton'> 
    <input type='button' value='Remove Button' id='removeButton'> 
    <input type='button' value='Get TextBox Value' id='getButtonValue'> 
</div> 

+1

阅读有关[__'Event delegation'__(https://learn.jquery.com/events/event-delegation/) – Rayon

+0

'$(父)。在(“#addButton”,“click”,callback);' –

+0

另外,由于您有多个删除/添加按钮,请使用class而不是ID –

回答

-1

使用event delegation

​​

OR

$("immediate_parent_id_or_class").on('click',".abc",function(){ 

     //add your script 
}) 
+0

ohhh伟大的人请加你的评论和解决方案 –

+0

'$(“immediate_parent_id_Class”)'class or id? FYI不是我downvote – guradio

+0

感谢@guradio它的错字。我已更正 –