2 回答

TA貢獻(xiàn)1851條經(jīng)驗 獲得超4個贊
解決此問題的一種方法是查看外部事件偵聽器的事件目標(biāo)。
rContainer.addEventListener("touchstart", function(event){
const targetId = event.target.getAttribute('id');
// don't set iActiveButton if you clicked empty space inside `rContainer`
if (targetId) {
// romanNumeralMap looks like { 'I': 1, 'II': 2, etc... }
iActiveButton = romanNumeralMap[targetId];
}
touchHandler();
}, false);
雖然這確實需要從羅馬數(shù)字映射到常規(guī)數(shù)字,但這樣您只需添加一個事件偵聽器!

TA貢獻(xiàn)1824條經(jīng)驗 獲得超5個贊
如果你真的想保持這樣的代碼邏輯并且只想重構(gòu),我會這樣做:
const buttonArray = [I, II, III, IV, V, VI, VII];
rContainer.addEventListener("touchstart", function(){
buttonArray.forEach((button, index) => {
button.addEventListener("touchstart", function(){iActiveButton = index;}, false);
}
touchHandler();
}, false);
但我完全同意這些評論,在每個事件上添加新的 EventListeners 似乎很奇怪。
添加回答
舉報