2013-03-20 44 views
0

我希望在其名称中添加已编号的输入(已成功完成),但如果为空(无法),也可以通过单击按钮将其删除。使用此代码,所有搜索类别的输入都将被删除。我只想要空的部分被删除。这里是我的尝试:单独删除输入

<script type="text/javascript"> 
// contains the counter for elements added 
window.__buttonClickCounter = 1; 

// Keep reference to container 
var c = document.getElementById('inputs'); 

// Click handler that appends to the contents of the container 
var clickhandler = function() { 
    c.innerHTML = c.innerHTML + "<input class='search' style='margin-bottom:4px;' type='search'   name='word" + window.__buttonClickCounter + "'/>"; 
    window.__buttonClickCounter++; 

    $('#removebtn').click(function() { 
     $('.search').remove(); 
    }); 
} 
</script> 

谢谢!

+0

你使用jQuery? – 2013-03-20 06:26:31

+0

当removebtn被点击时你将如何知道哪些输入已被删除 – 2013-03-20 06:27:11

回答

0

您可以使用jQuery如下写

$(function(){ 
    var counter = 0; 
    $('#addbtn').click(function(){ 
     $('#inputs').append('<input class="search" style="margin-bottom:4px;" type="search"   name="' + counter++ + '"/>') 
    }); 

    $('#removebtn').click(function(){ 
     $('.search').each(function(){ 
      var $this = $(this); 
      if(!$this.val()){ 
       $this.remove() 
      } 
     });  
    }); 
}) 

演示:Fiddle

+0

like,mega thanks – 2013-03-20 20:21:50

0

您可以调用.remove()这样的(因此只取出空之前过滤掉从jQuery对象非空的的):

$('#removebtn').click(function() { 
    $('.search').filter(function() {return !this.value}).remove(); 
}); 

如果.filter()回调返回true,则该项目被保留。如果返回false,则从结果jQuery对象中删除该值。因此,这开始于所有对象,然后只保留其中!this.valuetrue这意味着它保持其中this.value是虚假的(例如空的),因此只有空对象调用.remove()


或者多一点的可重用的方式:

// Reusable jQuery method for filtering out non-empty input values 
// Also filters out items that don't have a `.value` property 
$.fn.filterNonEmpty = function() { 
    return this.filter((function() {return !this.value}); 
}; 

// now use this new jQuery method 
$('#removebtn').click(function() { 
    $('.search').filterNonEmpty().remove(); 
});