【问题标题】:Remove Input Individually单独删除输入
【发布时间】:2013-03-20 06:23:50
【问题描述】:

我希望在他们的名字中添加编号输入(已经成功),但如果为空(不能),也可以通过单击按钮删除它们。使用此代码,所有搜索类输入都将被删除。我只想要删除空的。这是我的尝试:

<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> 

谢谢!

【问题讨论】:

  • 你在用 jquery 吗?
  • 当点击 removebtn 时,您将如何知道哪些输入必须被删除

标签: javascript jquery validation input


【解决方案1】:

你可以用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

【讨论】:

    【解决方案2】:

    您可以在像这样调用.remove() 之前从 jQuery 对象中过滤掉非空的对象(从而只删除空的对象):

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

    如果.filter() 回调返回true,则保留该项目。如果它返回false,则该值将从生成的 jQuery 对象中删除。所以,这从所有.search 对象开始,然后只保留!this.value 为true 的对象,这意味着它保留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();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2011-12-12
      • 1970-01-01
      • 2022-11-14
      相关资源
      最近更新 更多