Javascript jQuery.inArray()返回-1,即使它包含数组中的值
inarray函数返回-1,即使它在我的数组中有值 例如,如果我的数组中有['3'、'7'、'43'、'44'、'45'、'46'],当我选择一个值3或7时,它显示正确答案,然后当我选择其他值时,它返回-1 我的jQuery编码:Javascript jQuery.inArray()返回-1,即使它包含数组中的值,javascript,jquery,html,codeigniter,Javascript,Jquery,Html,Codeigniter,inarray函数返回-1,即使它在我的数组中有值 例如,如果我的数组中有['3'、'7'、'43'、'44'、'45'、'46'],当我选择一个值3或7时,它显示正确答案,然后当我选择其他值时,它返回-1 我的jQuery编码: $(document).on("change", '#level',function() { var valu = $('#level').val(); $.each(filterResults, function(index, item) { if
$(document).on("change", '#level',function() {
var valu = $('#level').val();
$.each(filterResults, function(index, item) {
if(jQuery.inArray(valu , item.id)!==-1){ //item.id has all array values
//my functions
}
}
});
然后是我的HTML编码
<select class="tb2" name="level" id="level">
<option value="">Select Level</option>
<option value="3">Pre Test</option>
<option value="7">Level 1</option>
<option value="43">Level 2</option>
<option value="44">Level 3</option>
<option value="45">Level 4</option>
<option value="46">Level 5</option>
</select>
console.logvalu,item.id返回
44 3
44 7
44 43
44 44
44 45
44 46item.id不包含数组,但包含单个id。$。inArray仅适用于数组。请尝试以下方法:
$(document).on("change", '#level',function() {
var valu = $('#level').val();
$.each(filterResults, function(index, item) {
if(valu == item.id){ // if item.id is equal to valu (e.g. '7' == '7')
// some code
}
});
});
或者,您可以使用筛选结果,以确定id是否在其中:
$(document).on("change", '#level',function() {
var valu = $('#level').val();
if( $.grep(filterResults, function(){return this.id == valu}).length ){
// some code
}
});
试一试
没有,每个
变量filterResults=['3'、'7'、'43'、'44'、'45'、'46'];
$document.onchange,“级别”,函数{
var valu=$'level'.val;
//$.eachfilterResults,函数索引,项{
ifjQuery.inarayValu,filterResults!=-1{
//我的职能
console.logvalu,$.inarayValu,filterResults
}
};
选择级别
预测试
一级
二级
三级
四级
五级
好的,代码中的问题是,您无缘无故地迭代结果数组。$.inArray已经在数组中进行了迭代,而您无需执行此操作;如果该值存在,它将返回该项的索引,如果不存在,它将返回-1。因此,您应该这样做:
var filterResults = ['3', '7', '43', '44', '45', '46'];
$('#level').change(function() {
var value = $(this).val();
if ($.inArray(value, filterResults) > -1) {
console.log(value + " EXISTS IN ARRAY");
} else {
console.log("FALSE");
}
});
获取进一步帮助。既然您已经在其他地方使用了$,为什么还要使用jQuery.inArray?为什么不使用本机indexOf函数?什么是filterResults?item.id有所有数组值?您确定吗?因为在小提琴中它可以很好地工作?请向我们显示console.logvalu,item.id的输出,将它们复制/粘贴到您的问题中。我们无法回答您的问题w不知道值包含什么。filterResults将从db获取所有值。item.id将存储从db.console.logvalu获取的id,item.id返回44 3 44 7 44 44 44 44 44 46
var filterResults = ['3', '7', '43', '44', '45', '46'];
$('#level').change(function() {
var value = $(this).val();
if ($.inArray(value, filterResults) > -1) {
console.log(value + " EXISTS IN ARRAY");
} else {
console.log("FALSE");
}
});