jQuery添加一个动态删除控件的链接

时间:2010-07-17 18:25:23

标签: javascript jquery html

我可以生成控件但无法删除它们。我正在尝试添加一个“链接”,它将调用一个函数来删除动态创建的控件。控件和链接彼此相邻。这是用于创建控件的Java脚本和标记:

<script type="text/javascript">
        $(function() { // when document has loaded

            //   <input id="File1" type="file" runat="server" size="60" />

            var i = $('input').size() + 1; // check how many input exists on the document and add 1 for the add command to work


            $('a#add').click(function() { // when you click the add link
                $('<p><input type="file" id="' + i + '" name="' + 'dynamic:' + i + '" /> <a href="#" id="' + 're' + i + ' " onclick="removeControl("' + '\'#' + i + '\''+ '")">+</a></p>').appendTo('body'); // append (add) a new input to the document.

                // if you have the input inside a form, change body to form in the appendTo
                i++; //after the click i will be i = 3 if you click again i will be i = 4s
            });

            function removeControl(controlId) {

                $(controlId).remove();
            }


        }); </script>


   <div>
        <a href="#" id="add">Add</a>

<br />


<p><input type="file" id="1" /></p>

    </div>

创建用于删除控件的链接的脚本无效。当我使用Firebug查看源代码时,onClick属性没有正确标记。

<a href="#" id="' + 're' + i + ' " onclick="removeControl("' + '\'#' + i + '\''+ '")">+</a>

我只是想添加一个链接来删除生成的控件和链接本身。

谢谢。

2 个答案:

答案 0 :(得分:2)

如果你想从通过javascript包含的Dom中删除一个元素,你需要attach or rebind an event handler

$('a.remove').live('click', function() {
  // Stuff to remove
});


工作解决方案:

<script type="text/javascript">
    $(function() {

        // Init counter
        var counter = 0;

        // Add Elements
        $('#add').click(function() {

            counter++ // Increment counter

            var add_input = '<p><input type="file" />';
            var add_link = '<a href="#" class="remove">Remove</a>';

            // Append Elements if counter smaller 4
            if (counter <= 4) {
                $('body').append('<p>' + add_input + add_link + '</p>');
            }
            return counter;
         });

         // Remove Elements
         $('.remove').live('click', function() {
             counter--; // Decrement counter
             $(this).parent('p').remove();
         });
     });
</script>

<a href="#" id="add">Add</a>

FYI-&GT;始终将dom插入物减少到最低限度。

答案 1 :(得分:0)

尝试将removeControl功能更改为:

function removeControl(driver) {
  $(driver).closest("p").remove();
}

然后,将对锚点中函数的调用更改为:

onclick="removeControl(this);return false;"

应该好好去......