2016-08-16 226 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它的錯字。我已更正 –