JQuery Append Html onclick function

JQuery Append Html onclick function

本文关键字:function onclick Html Append JQuery      更新时间:2023-09-26

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

用于添加多个文本框的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/

您可以在删除按钮上添加一个类,并在$("#TextBoxesGroup")上使用.on()添加remove事件。这样的

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

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

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