兩組 <li> 列表,點擊選中後需將兩組選中的 ID 拼接顯示。原代碼在循環中綁定事件,導致變量共享,只能獲取最後一項。
for (var i = 0; i < aLi.length; i++) {
aLi[i].onclick = function() { aId = this.id; ... }
}
// 所有 onclick 共享同一個 aId 變量,循環結束後 aId 為最後一個 li 的 id
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 || ''));
};
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>