0
我正在循環計數器,根據計數器值查找元素,並將事件綁定到與計數器匹配的集合。將JavaScript事件應用於錯誤的元素
僞代碼:
for index in counter
find elements of data attribute matching counter
attach click event to that matched query set
JS:
var groups = [];
$('.match-me').each(function(){
var group_id = $(this).data('instance');
if(groups.indexOf(group_id) < 0){
groups.push(group_id);
}
});
for(var i of groups){
window['test'+i] = $('*[data-instance=' + i + ']');
window['test'+i].each(function(){
$(this).on('click',function(){
//CONSOLE.LOG OF window['test'+i] OUTPUTS THE LAST MATCHED SET
window['test'+i].css('color','red');
});
});
}
的問題是內部在那裏我綁定的事件監聽,爲匹配的元素集合的變量總是最後匹配的集元素。我認爲通過在window
中創建動態全局變量,我可以逃避這個問題,但我不確定我做錯了什麼。
哦,JS結合Ÿü沒有工作PPL怎麼想 –
爲什麼你分配東西的窗口?全局是一個壞主意。 $('* [data-instance]')。on(「click」,function(){$(this).css('color','red');});' – epascarello
@epascarello我相信它試圖解決只引用最後一個變量的問題。你應該能夠接受下面的答案,並用'var etc'替換'window ['instances,以獲得相同的效果。 (不需要嘗試用數字對變量進行不同的命名 - 每個閉包執行它們將是不同的實例) – Katana314