简体   繁体   English

取消选中复选框时,从数组中删除元素

[英]remove element from array when checkbox unchecked

I add an element to an array when the checkbox is checked and I need to remove it when it is unchecked. 选中复选框后,我将元素添加到数组中,而未选中该元素时,则需要将其删除。 I use splice to remove an element. 我使用拼接来删除元素。 I just can't seem to call an event when it's unchecked. 取消选中后,我似乎无法调用该事件。 I tried using this: 我尝试使用此:

if ($('input[name="'+category+'"]:checked'))
    item_id[category] = $(this).attr("id");
else 
    item_id.splice(category, 1);

It adds the needed element ok, when the checkbox is checked, but it doesn't seem to remove it when it's unchecked. 选中该复选框后,它会添加所需的元素ok,但未选中该元素似乎并未将其删除。 Variable category is a loop variable and is correct. 变量类别是一个循环变量,是正确的。

If someone can work this out, it would be greatly appreciated. 如果有人可以解决这个问题,将不胜感激。

jQuery selectors always return an object whether an element is matched or not. jQuery选择器始终返回对象,无论元素是否匹配。

What you've effectively got is: 您实际上得到的是:

if (new Object())
    item_id[category] = $(this).attr("id");
else 
    item_id.splice(category, 1);

Objects are always truthy (no matter if it's an empty object, or an object John Resig initialized), so this if statement will never execute the else . 对象始终是真实的(无论它是空对象还是John Resig初始化的对象),因此,此if语句将永远不会执行else

What you're probably after is: 您可能想要的是:

if ($('input[name="'+category+'"]:checked').length)
    item_id[category] = $(this).attr("id");
else 
    item_id.splice(category, 1);

Which checks the length property instead. 而是检查length属性。

This still won't work however, as splice() will shift all elements in your array; 但是,这仍然不起作用,因为splice()会移动数组中的所有元素。 making the category wrong. 使category错误。

If your binding the event on a number of checkbox elements, it will be unwise to use .bind() (and it's counterparts .click() ), as this method will bind an event for each checkbox. 如果将事件绑定到多个复选框元素,则不明智的方法是使用.bind() (以及对应的.click() ),因为此方法将为每个复选框绑定一个事件。 Instead, use .live() , or .delegate() ; 而是使用.live().delegate() ; this will bind one event to an ancestor of all checkbox elements, and listen for event (using JavaScripts event bubbling), which is much more efficient. 这样会将一个事件绑定到所有复选框元素的祖先,并侦听事件(使用JavaScript事件冒泡),这效率更高。

Taking both of these points into consideration, you might fancy something like this. 考虑到这两点,您可能会喜欢这样的东西。

$(yourJquerySelector).live('change', function () {
    var category = '?' // (this.value ?)

    item_id[category] = this.checked ? this.id : undefined;
});

splice函数旨在返回删除的内容,因此请通过显示其返回值开始调试。

Change your if condition to: 将您的if条件更改为:

$('input[name="'+category+'"]').is(':checked')

As mentioned by Matt, your current if condition is a selector that returns a list of jQuery elements. 如Matt所述,您当前的if条件是一个选择器,该选择器返回jQuery元素列表。 Testing the number of elements returned (using the length property) would also do the trick. 测试返回的元素数量(使用length属性)也可以解决问题。

Not entirely sure what you are after to be honest, but here is my solution to this,hope it works for you in some way 不能完全确定您的诚实,但是这是我的解决方案,希望它对您有所帮助

Javascript Array - indexOf Method: http://www.tutorialspoint.com/javascript/array_indexof.htm Javascript Array-indexOf方法: http//www.tutorialspoint.com/javascript/array_indexof.htm

<script>

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

$(function() {

    var checkedItems = new Array();

    $(":checkbox").change(function () {
        if($(this).attr('checked'))
        {
        checkedItems.push($(this).attr("id"));
         }
        else
        {
        var index = checkedItems.indexOf($(this).attr("id"));
        checkedItems.splice(index,1);
        }
    });

});
</script>   

HTML HTML

<input type="checkbox" id="c1" value="1">
<input type="checkbox" id="c2" value="2">
<input type="checkbox" id="c3" value="3">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM