使用jQuery .remove()只删除第一个列表项

时间:2013-03-25 03:40:01

标签: jquery html

我有一个简单的表单,允许有人添加/删除额外的电话号码。出于某种原因,我无法在我的Javascript中看到错误。用户可以添加新号码作为列表项而不会出现任何问题 - 每个列表项都有一个按钮来删除列表项。如果用户单击第一个列表项删除按钮,则该项将被删除。使用JS添加的列表项都不会从页面中删除。

这看起来很简单,但我很难过。我花了最后两个小时试图通过stackoverflow和google上的许多搜索来解决这个问题。我知道当它解决后我会感到愚蠢,但我可以对此有所帮助。

HTML

<ul class="telRow">
  <li id="telid_1234">
    ONE <button class="telRowRemove">-</button>
  </li>
</ul>

<div>
  <button class="telRowAdd">+</button>
</div>

<div id="errors">No errors</div>

<div class="emptyTel" style="display: none;">
<input type="text" name="tel_no[]" />
<button class="telRowRemove">-</button> 
</div>

JS

$(document).ready(function(){

  $('.telRowAdd').on('click', function() {
     var Container = $('ul.telRow');
     var newrow = '<li>ONE <button class="telRowRemove">-</button></li>';
     Container.append(newrow);
      $('#errors').text('Added');
  });

  $('.telRowRemove').click(function() {
      $(this).parent('li').remove();
      $('#errors').text('Removed');
  });
});

删除按钮有一个.telRowRemove类,所以理论上点击按钮会触发$('。telRowRemove')。点击,但它只对页面上的原始列表项执行此操作,其余的都没有列表项目。

我在JS Bin上有一个示例设置http://jsbin.com/omanij/1/edit

3 个答案:

答案 0 :(得分:3)

您的选择器仅将事件绑定到查找时存在的元素。使用事件委派来匹配稍后出现的事件:

$('#parent_of_tel_rows').on('click', '.telRowRemove', function() {
    $(this).parent('li').remove();
    $('#errors').text('Removed');
});

答案 1 :(得分:0)

以下按钮不起作用的原因是它们被动态添加到DOM中,并且绑定到的click事件不会为将来的元素触发。

使用.on()代替,它将确保未来的元素也被绑定。

请在此处查看更新后的示例:http://jsbin.com/omanij/5/edit

答案 2 :(得分:0)

你可以在jsfiddle中找到下面的工作模型:

http://jsfiddle.net/btjcz/

$('.telRowAdd').on('click', function () {
        var Container = $('ul.telRow');
        var newrow = $('<li>ONE </li>');
        var btnRemove = $('<button class="telRowRemove">-</button>');

        btnRemove.click(function () {
            $(this).parent('li').remove();
            $('#errors').text('Removed');
        });
        newrow.append(btnRemove);



        Container.append(newrow);
        $('#errors').text('Added');
    });