在 jQuery 中动态删除文本框,而无需使用任何 JavaScript

remove a textbox dynamically in jquery without using any javascript

本文关键字:JavaScript 任何 jQuery 动态 删除 文本      更新时间:2023-09-26

这是我的代码,我尝试创建动态添加/删除文本框。 当我单击删除按钮时,所有内容都将被删除,我该怎么办(或请在此代码中指定我的错误。 我想一个接一个地删除..谁能告诉我?提前谢谢..

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>dynamic add button</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>              
<script>
    $(document).ready(function () {
        $('<button/>').attr({ 'id': 'add' }).appendTo("body");
        $("#add").text("Add Field");
        $('<div/>').attr({ 'id': 'items' }).appendTo("body");
        $('<div/>').attr({ 'type': 'text', 'name': 'input[]' }).appendTo("#items");
        $("#add").click(function (e) {
            //Append a new row of code to the "#items" div
            var text1 = $('<div/>').attr({ 'id':'div2','type': 'text', 'name': 'input[]' });
           var text2 = $('<input/>').attr({ 'id': 'i1', 'type': 'text', 'name': 'username', 'size': '25' });
           var text3 = $('<button/>').attr({ 'id': 'del' }).text("Delete");
            $("#div2").append(text2, text3);
            $("#items").append(text1);
            $('<br/>').insertAfter(text3);
        });
        //delete function
        $("body").on("click","#del",function (e) {
            $(this).parent("div").remove();
        });       
    });      
   </script>
</head>
<body>
</body>
</html>

jQuery是javascript,但我认为这就是你的意思。这是JSfiddle:http://jsfiddle.net/wfthf2qc/

问题是你为所有文本字段(#div2(保留了相同的id,所以当你附加新字段时,jquery一直附加到#div2的第一个出现。然后,当您调用 delete 函数时,它会删除现在包含所有字段的父div。

在我的代码中,我创建了一个count变量,每次单击"添加"按钮时都会不断计数,并使用它来创建唯一的div 名称(div1、div2、div3 等(,因此 jquery 知道在哪里附加新字段。

我还在$("#div" + count).append(text2, text3);之前$("#items").append(text1);上移,因为它放在第一次单击"添加"按钮失败之后,因为它没有任何div 容器可以附加。

    $("#items").append(text1);
    $("#div" + count).append(text2, text3);
    $('<br/>').insertAfter(text3);

我个人认为可能有更优雅的解决方案,但我不想过多地更改您的代码