将事件添加到动态创建的按钮

时间:2016-08-16 05:03:16

标签: javascript jquery html

这里我正在创建动态单选按钮,文本区域和单击事件,但我的单击事件添加和删除按钮不适用于动态创建的按钮。我尝试使用jquery的click事件,但它没有像expecte一样工作。如何在我的场景中添加.on 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 个答案:

答案 0 :(得分:-1)

使用event delegation

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

    //add your script
})

OR

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

        //add your script
})