0
我有一個函數可以獲取窗口中的所有選項卡,然後通過爲每個選項卡添加複選框來更新popup.html頁面。做完這些之後,會有第二個for循環添加事件偵聽器,用於更新包含複選框值的字典。問題是,我點擊的任何複選框只會更新字典中的最後一個元素。將eventListeners添加到for循環中的複選框chrome擴展
下面是代碼:
function viewTabs() {
var queryInfo = {lastFocusedWindow: true};
// Go through all the tabs open, and add them to the scrollview along with a number and checkbox
chrome.tabs.query(queryInfo, function(tabs) {
document.getElementById("openLinks").innerHTML = "";
(function() {
for (i = 0; i < tabs.length; i++) {
// add checkboxes to each link for the user to include or disclude
document.getElementById("openLinks").innerHTML +=
"<li><input type=\"checkbox\" id = \"" + i.toString() + "\" checked>" +
tabs[i].title + "</li>";
checkedTabsArr[i.toString()] = true;
}
for (i = 0; i < tabs.length; i++) {
document.getElementById(i.toString()).addEventListener("click",
function() {
console.log(checkedTabsArr);
checkedTabsArr[i.toString()] = !checkedTabsArr[i.toString()];
});
}
}());
});
}
這裏是輸出(我點擊不同的複選框不只是6):
Object {0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true}
Buttons.js:174 Object {0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true, 7: true}
Buttons.js:174 Object {0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true, 7: false}
Buttons.js:174 Object {0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true, 7: true}
Buttons.js:174 Object {0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true, 7: false}
Buttons.js:174 Object {0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true, 7: true}
Buttons.js:174 Object {0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true, 7: false}
Buttons.js:174 Object {0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true, 7: true}
Buttons.js:174 Object {0: true, 1: true, 2: true, 3: true, 4: true, 5: true, 6: true, 7: false}
我已經有和沒有封閉審判。
我剛測試過它。現在的問題是,當我點擊複選框時,什麼也沒有發生。我添加了一個console.log語句,但單擊複選框時沒有任何反應 – abden003
剛更新了答案。這應該爲你做。 –
修復了這個問題,但爲什麼?是因爲你使用了jquery嗎? – abden003