我有一个带ID的数组。应该删除数组中没有数据函数ID的元素。所以我使用属性data-functionID遍历所有元素,如果数组中没有ID,则删除它。
现在我的问题是jQuery.inArray()总是返回-1(在变量访问中),我似乎无法找出原因。
//html-example
<button data-functionID="j1_1" onclick="doStuff()">Button 1</button>
<button data-functionID="j1_24" onclick="doOtherStuff()">Button 2</button>
下面定义的数组是使用mysqli_fecth_all-query用PHP编写的,我只是保存在变量$role
中,编码为JSON:
var role = JSON.parse('<?php echo json_encode($role)?>');
在PHP之后它看起来像这样:
// defining array
var role = JSON.parse('[["j1_1"],["j1_24"],["j1_63"],["j1_62"],["j1_61"],["j1_60"],["j1_59"],["j1_57"],["j1_58"],["j1_56"],["j1_55"],["j1_54"],["j1_53"],["j1_51"],["j1_52"],["j1_50"],["j1_49"],["j1_48"],["j1_47"],["j1_46"],["j1_45"],["j1_44"],["j1_43"],["j1_42"],["j1_41"],["j1_40"],["j1_39"],["j1_38"],["j1_37"],["j1_36"],["j1_35"],["j1_34"],["j1_33"],["j1_32"],["j1_31"],["j1_30"],["j1_29"],["j1_28"],["j1_27"],["j1_26"],["j1_25"],["j1_23"],["j1_22"],["j1_21"],["j1_20"],["j1_19"],["j1_18"],["j1_17"],["j1_16"],["j1_15"],["j1_14"],["j1_13"],["j1_12"],["j1_11"],["j1_10"],["j1_9"],["j1_8"],["j1_7"],["j1_6"],["j1_5"],["j1_4"],["j1_3"],["j1_2"]]');
// test
$("[data-functionID]").each(function(e){
functionID = $(this).attr('data-functionID');
var access = jQuery.inArray(functionID, role);
console.log(functionID + ':' + access);
if(access == -1){
$(this).remove();
}
});
答案 0 :(得分:0)
所以我解决了我的问题,更改了要从mysqli_query
创建的数组以循环遍历mysqli_fetch_assoc
并手动创建数组以获得一维数组。
$role = array();
while($row = mysqli_fetch_assoc($result)){
$role[] = $row['functionID'];
}
这将javascript输出作为一维数组:
var role = JSON.parse('["j1_1","j1_24","j1_63","j1_62","j1_61","j1_60","j1_59","j1_57","j1_58","j1_56","j1_55","j1_54","j1_53","j1_51","j1_52","j1_50","j1_49","j1_48","j1_47","j1_46","j1_45","j1_44","j1_43","j1_42","j1_41","j1_40","j1_39","j1_38","j1_37","j1_36","j1_35","j1_34","j1_33","j1_32","j1_31","j1_30","j1_29","j1_28","j1_27","j1_26","j1_25","j1_23","j1_22","j1_21","j1_20","j1_19","j1_18","j1_17","j1_16","j1_15","j1_14","j1_13","j1_12","j1_11","j1_10","j1_9","j1_8","j1_7","j1_6","j1_5","j1_4","j1_3","j1_2"]');