首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JavaScript 獲取並拼接兩個列表選項 ID 的正確閉包寫法

     編輯:程式設計綜合問答

問題現場

兩組 <li> 列表,點擊選中後需將兩組選中的 ID 拼接顯示。原代碼在循環中綁定事件,導致變量共享,只能獲取最後一項。

錯誤代碼分析

for (var i = 0; i < aLi.length; i++) {
  aLi[i].onclick = function() { aId = this.id; ... }
}
// 所有 onclick 共享同一個 aId 變量,循環結束後 aId 為最後一個 li 的 id

正確寫法:ES6 let / IIFE / 箭頭函數

方案一:let 形成塊級作用域(推薦)

let aId, bId;
for (let i = 0; i < aLi.length; i++) {
  aLi[i].onclick = function() {
    aId = this.id;
    document.getElementById('ss').textContent = this.textContent;
  };
}
for (let j = 0; j < bLi.length; j++) {
  bLi[j].onclick = function() {
    bId = this.id;
    document.getElementById('cc').textContent = this.textContent;
  };
}
document.getElementById('btn').onclick = () => {
  alert((aId || '') + (bId || ''));
};

方案二:立即執行函數(IIFE)捕獲當前值

for (var i = 0; i < aLi.length; i++) {
  (function(index) {
    aLi[index].onclick = function() {
      aId = this.id;
      // ...
    };
  })(i);
}

方案三:事件委託(性能更優)

document.getElementById('choose1').addEventListener('click', e => {
  if (e.target.tagName === 'LI') {
    aId = e.target.id;
    document.getElementById('ss').textContent = e.target.textContent;
  }
});
document.getElementById('choose2').addEventListener('click', e => {
  if (e.target.tagName === 'LI') {
    bId = e.target.id;
    document.getElementById('cc').textContent = e.target.textContent;
  }
});

完整可運行示例

<p>第一題:<u id="ss"></u></p>
<ul id="choose1"><li id="a1">哈哈</li><li id="a2">呵呵</li></ul>
<p>第二題:<u id="cc"></u></p>
<ul id="choose2"><li id="b1">Java</li><li id="b2">Python</li></ul>
<button id="btn">提交</button>

<script>
const choose1 = document.getElementById('choose1');
const choose2 = document.getElementById('choose2');
let aId = '', bId = '';

choose1.addEventListener('click', e => {
  if (e.target.matches('li')) {
    aId = e.target.id;
    document.getElementById('ss').textContent = e.target.textContent;
  }
});
choose2.addEventListener('click', e => {
  if (e.target.matches('li')) {
    bId = e.target.id;
    document.getElementById('cc').textContent = e.target.textContent;
  }
});
document.getElementById('btn').addEventListener('click', () => {
  alert('拼接結果:' + aId + bId);
});
</script>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved