javascript - 使用 jQuery 动态添加删除行

标签 javascript jquery

我有这样的代码...

<html>
    <head>
        <title>test</title>
        <script type="text/javascript">
            var counter = 2;
            var idCounter= 3;
            function addNew() {
            if(counter<=5){
                // Get the main Div in which all the other divs will be added
                var mainContainer = document.getElementById('mainContainer');
                // Create a new div for holding text and button input elements
                var newDiv = document.createElement('div');
                newDiv.id='divs'+counter;
                // Create a new text input
                var newText = document.createElement('input');
                var newText1 = document.createElement('input');
                newText.type = "input";
                newText.id="ans"+(idCounter);
                idCounter++;
                newText1.type = "input";
                newText1.id="ans"+(idCounter);
                idCounter++;
               // newText.value = counter;
                // Create a new button input
                var newDelButton = document.createElement('input');
                newDelButton.type = "button";
                newDelButton.value = "Remove";

                // Append new text input to the newDiv
                newDiv.appendChild(newText);
                newDiv.appendChild(newText1);
                // Append new button input to the newDiv
                newDiv.appendChild(newDelButton);
                // Append newDiv input to the mainContainer div
                mainContainer.appendChild(newDiv);
                counter++;

                // Add a handler to button for deleting the newDiv from the mainContainer
                newDelButton.onclick = function() {
                        mainContainer.removeChild(newDiv);
                        counter--;
                }
            }
            else{
                alert('Only 5 rows are allowed');
            }}sss
            function removeRow(divId){
                 mainContainer.removeChild(divId);
                 counter--;
            }

        </script>
    </head>

    <body >
        <div id="mainContainer">
            <div><input type="button" value="Add New Row" onClick="addNew()"></div>
            <div id="div1"><input type="text" id="ans1"><input type="text" id="ans2"><input type="button" value="Remove" onClick ="javascript:removeRow(div1);"></div>
        </div>
    </body>
</html>

我想使用 jQuery 实现相同的效果。我还需要在每个文本框中输入的值。请帮忙。

最佳答案

好吧,因为我没有更好的事可做,老实说,我很好奇,所以我把它放在一起。正如我在上面的评论中所暗示的,我不是特别喜欢你的布局方式,所以我使用了以下 (x)html:

<form action="#" method="post">
    <fieldset id="rows">
        <ul>
            <li>
                <input type="text" id="ans1" name="ans1" />
                <input type="text" id="ans2" name="ans2" />
            </li>
        </ul>
    </fieldset>
    <fieldset id="controls">
        <button id="addRow">add</button>
        <button id="removeRow" disabled>remove</button>
    </fieldset>
</form>

使用下面的 jQuery(虽然我显然没有优化或完善它,但它应该满足您的要求):

$(document).ready(
    function(){
        $('#addRow').click(
            function() {
                var curMaxInput = $('input:text').length;

                $('#rows li:first')
                    .clone()
                    .insertAfter($('#rows li:last'))
                    .find('input:text:eq(0)')
                    .attr({'id': 'ans' + (curMaxInput + 1),
                           'name': 'ans' + (curMaxInput + 1)
                          })
                    .parent()
                    .find('input:text:eq(1)')
                    .attr({
                        'id': 'ans' + (curMaxInput + 2),
                        'name': 'ans' + (curMaxInput + 2)
                    });
                $('#removeRow')
                    .removeAttr('disabled');
                if ($('#rows li').length >= 5) {
                    $('#addRow')
                        .attr('disabled',true);
                }
                return false;
            });

        $('#removeRow').click(
            function() {
                if ($('#rows li').length > 1) {
                    $('#rows li:last')
                        .remove();
                }
                if ($('#rows li').length <= 1) {
                    $('#removeRow')
                        .attr('disabled', true);
                }
                else if ($('#rows li').length < 5) {
                    $('#addRow')
                        .removeAttr('disabled');

                }
                return false;
            });
    });

JS Fiddle demo of the above

但是,我不确定您的意思:

I also need the values entered in each of these textboxes.

如果您能解释这意味着什么,或者您希望它们如何可用(理想情况下,为什么它们已经对您可用)我会尽力提供帮助。

关于javascript - 使用 jQuery 动态添加删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4359804/

相关文章:

javascript - Sapui5:模型没有被破坏

javascript - 在函数中使用 eval 来替换图层名称上的前缀?

javascript - Backbone.js 和 Require.js : Mismatched anonymous define() module: function (_, 主干){

php - 如何从我的站点缓存脚本和图像?

Javascript/AJAX/使用 JSON 发送到服务器文本和文件

javascript - 将响应式 div 高度设置为等于其同级

javascript - Knockout.js:如何获取已注册的组件实例?

javascript - jquery 滚动插件错误

javascript - IE 11 错误 - 图像在标签内的表单内 - 需要保留鼠标事件

jquery - 在响应式布局中排除 jQuery 脚本