我想傳遞一個數組,我已經保存爲var。我在父函數中聲明var,並在父函數中添加arr作爲參數。然後,我將arr作爲回調調用中的參數。 控制檯告訴我linksA是未定義的。從函數傳遞變量作爲參數
var supportLists = function(selector, arr) {
var parentList = document.getElementById(selector);
var theList = parentList.querySelectorAll("a");
var linksA = [
"http://www.example.com",
"http://www.example.com/path2",
"1",
"2",
"4",
"3",
"5",
"6",
"7"
];
var linksB = [
"1",
"2",
"3"
];
var linksC = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12"
];
var linksD = [
"1",
"2"
];
var linksE = [
"1",
"2",
"3"
];
var linksF = [
"1",
"2",
"3",
"4",
"5",
"6"
];
var linksG = [
"1",
"2",
"3"
];
var linksH = [
"1",
"2",
"3",
"4"
];
var linksI = [
"1"
];
var linksJ = [
"1",
"2",
"3",
"4",
"5"
];
function processLi(listItems, links) {
for (var i = 0; i < links.length; i++) {
listItems.forEach(function(item, index) {
item.href = links[index];
item.target = "_blank";
});
}
}
processLi(theList, arr);
};
supportLists("support-list", linksA);
supportLists("support-list-b", linksB);
supportLists("support-list-c", linksC);
supportLists("support-list-d", linksD);
supportLists("support-list-e", linksE);
supportLists("support-list-f", linksF);
supportLists("support-list-g", linksG);
supportLists("support-list-h", linksH);
supportLists("support-list-i", linksI);
supportLists("support-list-j", linksJ);
您試圖在聲明它們的函數外部使用那些'links'變量。 – 2016-09-15 17:13:43
添加@squint答案,你可以聲明數組在相同的範圍上,函數將被調用並將它們作爲參數傳遞給函數,或者傳遞鏈接數組的名稱作爲輸入參數函數並在其中有一個邏輯來選擇和使用正確的數組。 – GCSDC
如果我將它們放入processLi函數中,會得到相同的錯誤。 除此之外,我不是在調用中使用它們,而是坐在父函數內部,而不是回調? – ardev