【问题标题】:Removal of elements from an array not working in jquery从数组中删除元素在 jquery 中不起作用
【发布时间】:2015-09-09 13:23:16
【问题描述】:

我有一组从数据库中选择查询时生成的复选框。

<input type="checkbox" name="grade_checkbox[]" class="grade_checkbox" value="1">
//value of checkbox is getting from database table.I have put value =1 as an example

单击每个复选框时,我将复选框的值存储到一个数组中。

var selected_grades = [];
$(".grade_checkbox").click(function(){
  if(!$(this).is(":checked")
  {
     //remove the checkbox value from the array since it is unchecked
     if($.inArray($(this).val(),selected_grades)!==-1)
        {
            selected_grades.remove(selected_grades.indexOf($(this).val()));
        } 
  }
   selected_grades = $('input:checkbox:checked.grade_checkbox').map(function () {
                            return this.value;
                            }).get();
    console.log(selected_grades);
});

selected_grades 是一个数组,用于存储被选中的复选框值。

当我选中每个复选框时,数组selected_grades 会显示在控制台中,其中包含所有选中的复选框值。

当我尝试取消选中任何复选框时,我实际上是在尝试从上述数组中删除该元素(如果存在)。但是我收到以下错误

TypeError: selected_grades.remove is not a function

我不知道为什么会这样。

【问题讨论】:

标签: jquery arrays checkbox


【解决方案1】:

您可以使用.splice() 简单地做到这一点

selected_grades.splice(selected_grades.indexOf($(this).val()), 1);

例如:-

假设我们想从下面的数组中删除3。我们可以像下面那样做

var array = [2, 3, 4, 5];
var index = array.indexOf(3);

var d = array.splice(index, 1);
console.log(d);     // returns [3]
console.log(array); // returns [2, 4, 5]

【讨论】:

  • 我可以知道splice()的第二个参数1的意义是什么。我找不到它-@PalaSH
  • @Techy:最后一个参数表示一个整数,表示要删除的旧数组元素的数量。如果该数字为 0,则不删除任何元素。在这种情况下,我们只想删除一个元素,所以它会被删除。
  • @Techy:酷。我还添加了一个演示示例供参考。
猜你喜欢
  • 2013-02-02
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2012-05-10
  • 2018-03-18
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
相关资源
最近更新 更多