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

时间:2010-11-23 09:23:35

标签: javascript jquery arrays checkbox

选中复选框后,我会向数组中添加一个元素,并且在取消选中时我需要将其删除。我使用splice删除元素。当它未被检查时,我似乎无法调用事件。我试过用这个:

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

当选中复选框时,它会添加所需的元素,但是当它未选中时似乎不会删除它。变量类别是一个循环变量,是正确的。

如果有人可以解决这个问题,我们将不胜感激。

4 个答案:

答案 0 :(得分:2)

jQuery选择器总是返回一个对象,无论元素是否匹配。

你有效得到的是:

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

对象始终是真实的(无论它是空对象,还是John Resig初始化的对象),因此if语句永远不会执行else

你可能会追求的是:

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

而是检查length属性。

然而,这仍然不起作用,因为splice()将移动数组中的所有元素;使category错误。

如果您在多个复选框元素上绑定事件,则使用.bind()(和它的对应.click())是不明智的,因为此方法将为每个复选框绑定一个事件。相反,请使用.live().delegate();这会将一个事件绑定到所有复选框元素的祖先,并侦听事件(使用JavaScripts事件冒泡),这样效率会更高。

考虑到这两点,你可能会喜欢这样的东西。

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

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

答案 1 :(得分:1)

splice函数用于返回已删除的内容,因此请通过显示其返回值来启动调试。

答案 2 :(得分:1)

将您的if条件更改为:

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

如Matt所述,您当前的if条件是一个返回jQuery元素列表的选择器。测试返回的元素数量(使用length属性)也可以解决问题。

答案 3 :(得分:1)

说实话并不完全确定你是什么,但这是我的解决方案,希望它能以某种方式为你服务

Javascript数组 - 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

<input type="checkbox" id="c1" value="1">
<input type="checkbox" id="c2" value="2">
<input type="checkbox" id="c3" value="3">
相关问题