你能幫我解決這個問題嗎?我無法爲我的其他功能使用return x值。我想要點擊某個元素時,然後腳本加載單擊元素的ID,然後使用此ID更改元素的顏色。 對我的問題有更好的解決方案嗎? (在純JS中,不在Jquery中) 謝謝。Javascript從元素獲取ID然後使用它
<p id="1">foo</p>
<p id="2">bar</p>
<p id="3">baz</p>
<script>
document.addEventListener('click', function(e) {
x=e.target.id;
return x
});
document.getElementById(x).onclick =
function(x) {
if (document.getElementById(x).style.backgroundColor !== 'yellow') {
document.getElementById(x).style.backgroundColor = 'yellow';
}
else {
document.getElementById(x).style.backgroundColor = 'red';
}
};
</script>
您必須使用僅一個街區 –