2015-02-11 109 views
-2

我有位置,像这样jQuery的inarray总是返回true

var pre_locations = []; 
pre_locations.push(result.locations); 

这将返回以下

["BB,BD,BL,CA"] 

但现在我有相同的价值观一些复选框,这样一个阵列的阵列如果数组中的位置与复选框具有相同的值,请将复选框标记为选中状态。但是,我有以下和它不工作,我不知道为什么

$(".postcode_check").each(function(){ 
     if($.inArray($(this).val(), pre_locations) > 0){ 
      $(this).prop('checked', true); 
     } 
}); 
+1

你能示出了示例pre_locations中的数据(例如console.log结果)?和.postcode_check的HTML? – 2015-02-11 15:36:26

+0

数据只是数据库中的一个数组。所以BB,BD,BL,CA – 2015-02-11 15:37:08

+5

除非你犯了一个错字,你的数组只是一个字符串 - 这是故意的吗? – 2015-02-11 15:37:16

回答

0

我相信,你的位置,你的结果是,回来用逗号分隔的字符串。这是基于上述情况的假设。只需拆分结果并修复您的状况以检查> -1

这工作正常。

var pre_locations = result.locations.split(','); 

$(".postcode_check").each(function(){ 
    if ($.inArray($(this).val(), pre_locations) > -1) { 
    $(this).prop('checked', true); 
    } 
}); 

演示

var result = { locations : "BB,BD,BL,CA" }; 
 

 
$(document).ready(function() { 
 
    createCheckboxes(['A','B','C','D'], 2); // Generate 16 checkboxes (AA->DD) 
 

 
    var pre_locations = result.locations.split(','); 
 

 
    $(".postcode_check").each(function(){ 
 
    if ($.inArray($(this).val(), pre_locations) > -1) { 
 
     $(this).prop('checked', true); 
 
    } 
 
    }); 
 
}); 
 

 
// [IGNORE] These function are used to generate the checkboxes. 
 
function createCheckboxes(alphabet, size) { 
 
    $.each(permutations(alphabet, size), function(i, p) { 
 
    $('body').append($('<div>').addClass('cb-wrapper') 
 
     .append($('<label>').addClass('cb-label').html(p.join(''))) 
 
     .append($('<input type="checkbox">').addClass('postcode_check').val(p.join('')))); 
 
    if (i % alphabet.length == alphabet.length-1) $('body').append($('<br>')); 
 
    }); 
 
} 
 
function permutations(series, size) { 
 
    return zeroFill(Math.pow(series.length,size)).map(function(r,i) { 
 
    return zeroFill(size).map(function(c,j) { 
 
     return series[Math.floor(i/Math.pow(series.length,j))%series.length]; 
 
    }).reverse(); 
 
    }); 
 
} 
 
function zeroFill(n) { 
 
    return new Array(n+1).join('0').split(''); 
 
}
.cb-wrapper, .cb-label { display: inline-block; } 
 
.cb-wrapper { width: 60px; } 
 
.cb-label { display: inline-block; width : 24px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

0

您需要使用concat而不是push

push()方法添加新元素添加到数组的末尾:

var a = [1, 2]; 
a.push([3, 4]); 
// a is [1, 2, [3, 4]] 

concat()产生通过串联阵列的新数组:

var a = [1, 2]; 
var b = a.concat([3, 4]); 
// b is [1, 2, 3, 4] 

Demo