jQuery.inArray没有按预期执行

时间:2014-12-13 17:14:05

标签: javascript jquery

我编写了以下函数来检查基于一组特征过滤器的复选框,这是一个由单独的function返回的数组。

$(function() {
    $('#device_form').find(':checkbox[name^="feature_filters"]').each(function () {
      $(this).prop("checked", (jQuery.inArray($(this).attr('data-feature-id'), feature_filters) != -1 ));
      console.log("feature_filters " + jQuery.type(feature_filters) + " " + feature_filters);
      console.log("data-feature-id " + $(this).attr('data-feature-id'));
      console.log("In Array Result " + jQuery.inArray($(this).attr('data-feature-id'), feature_filters));
    });
});

日志很有趣:

feature_filters array 2,10
data-feature-id 9
-> inArray Result -1

feature_filters array 2,10
data-feature-id 2
-> inArray Result -1

正如您所看到的,对于最后一个示例,inArray结果应为0。我做错了什么?

1 个答案:

答案 0 :(得分:0)

正如@adeneo所建议的,我需要将data-feature-id转换为整数格式,以便inArray正常工作。这是我的答案:

  $(function() {
    $('#device_form').find(':checkbox[name^="feature_filters"]').each(function () {
      num = parseInt($(this).attr('data-feature-id'), 10);
      $(this).prop("checked", (jQuery.inArray(num, feature_filters) != -1 ));
    });
  });