JQuery附加Html onclick函数

时间:2013-05-06 06:56:29

标签: javascript jquery

我试图均匀地删除文本框。我的意思是每个文本框我想要删除按钮。如果我单击删除按钮我想删除文本框

用于添加多个文本框的Html

<pre><div id="TextBoxDiv1">
                    <label style="float: none;"> Bus Model &nbsp;&nbsp;&nbsp;
                    <input style="width: 150px;" type="text" value="" class="validate[required,custom[onlyNumberSp]]" name="numsValid" id="numsValid">
                    <img src="images/india_rupess.png" style="margin-left:18px;"> :</label>
                    <input style="width: 150px;" type="text" value="" class="validate[required,custom[onlyNumberSp]]" name="numsValid" id="numsValid">
                    <label style="float: none;margin-left: 16px;"><span class="font-dollar">﹩</span>&nbsp; :</label>
                    <input style="width: 150px;" type="text" value="" class="validate[required,custom[onlyNumberSp]]" name="numsValid" id="numsValid">
                    &nbsp;&nbsp;<a href="javascript:;" id="addButton">Add</a>&nbsp;&nbsp;<a href="javascript:;" id="removeButton">Remove</a>
                    </div></pre>

这是我的剧本

<pre>var counter = 2;
$("#addButton").click(function () {


    $("#TextBoxesGroup").append('<div id="TextBoxDiv'  + counter +   '" class="textadd""><label style="float: none;"> Bus Model &nbsp;&nbsp;&nbsp;<input style="width: 150px;margin-left:3px;" type="text" value="" class="validate[required,custom[onlyNumberSp]]" name="bus' + counter +   '" id="numsValid"><img src="images/india_rupess.png" style="margin-left:21px;"> :</label><input style="width: 150px;margin-left:3px;" type="text" value="" class="validate[required,custom[onlyNumberSp]]"  name="rs' + counter +   '" id="numsValid"><label style="float: none;margin-left: 19px;"><span class="font-dollar">﹩</span>&nbsp; :</label><input style="width: 150px;margin-left:2px;" type="text" value="" class="validate[required,custom[onlyNumberSp]]"  name="dollar' + counter + '" id="numsValid">&nbsp;&nbsp;<a href="javascript:;" onClick="javascript:alert("test");"   >Remove</a></div>');

counter++;;

});

点击查看http://jsfiddle.net/b8DRT/

2 个答案:

答案 0 :(得分:4)

您可以在删除按钮上添加一个课程,并在$("#TextBoxesGroup")上使用.on() 添加删除事件。喜欢这个

    $("#TextBoxesGroup").on('click', '.removeButton', function(){
        $(this).closest('div').remove();        
    });

这是更新后的fiddle ..

答案 1 :(得分:0)

id对于完整文档中的HTML元素是唯一的。您将同一个id分配给多个元素。其次,当您使用click附加事件处理程序时,它们将绑定到DOM中已存在的元素,而不是稍后要添加的元素。如果要附加Click事件处理程序,则应使用如下on方法:

$(document).on('click', '.removeButton', function(e){
    // your logic here...
});
相关问题