2 回答

TA貢獻1804條經驗 獲得超3個贊
您正在使用.querySelector()
它返回文檔中與提供的選擇器匹配的第一個元素。
要獲取多個元素,您需要使用.querySelectorAll()
它將返回與選擇器匹配的元素的靜態NodeList。此時,您需要循環遍歷 NodeList 并操作類。
但是,由于您嘗試定位事件調用元素,我認為您可以通過引用該元素來簡化它。
function?toggleColor(el,?e)?{ ????el.classList.toggle('disable'); ????el.classList.toggle('active'); }
并將您的onclick
處理程序更改為onclick="toggleColor(this,event);"
這是一個快速片段:
function toggleColor(el, e) {
? ? el.classList.toggle('disable');
? ? el.classList.toggle('active');
}
.disable { color: #ccc }
.active? { color: #0095ee; }
<div>
? ? <svg class="disable" onclick="toggleColor(this,event);" viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="currentColor" stroke-linecap="round" stroke-linejoin="round" class="css-i6dzq1"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg>
?</div>
?<div>
? ? ?<svg class="disable" onclick="toggleColor(this,event);" viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="currentColor" stroke-linecap="round" stroke-linejoin="round" class="css-i6dzq1"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg>
?</div>
?<div>
? ? ?<svg class="disable" onclick="toggleColor(this,event);" viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="currentColor" stroke-linecap="round" stroke-linejoin="round" class="css-i6dzq1"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg>
?</div>

TA貢獻1801條經驗 獲得超8個贊
為什么會發生這種情況?
由于有多個具有 類的元素heart
,因此它不知道要在哪個元素上執行腳本!這就像一個老師試圖給鮑勃打電話,而班級里有 5 個叫鮑勃的人。
我們該如何解決這個問題?
onclick
您可以通過在腳本中提供元素的引用來更改 中的函數,如下所示: onclick="myFunction(this)"
?,F在,在 javascript 中,您可以對元素執行任何您需要的操作。
嘗試一下!運行下面的例子!
function toggleColor(element) {
toggleHeart = element;
if(toggleHeart.classList.contains('disable')) {
toggleHeart.classList.remove('disable');
toggleHeart.classList.add('active');
} else {
toggleHeart.classList.remove('active');
toggleHeart.classList.add('disable');
}
}
.disable {
color: blue;
}
.active {
color: red;
}
<!-- vvv below we used the "this" keyword which references to the svg element -->
<div onclick="toggleColor(this)" class="disable">
Click Me!
</div>
<div onclick="toggleColor(this)" class="disable">
Click Me!
</div>
<div onclick="toggleColor(this)" class="disable">
Click Me!
</div>
<div onclick="toggleColor(this)" class="disable">
Click Me!
</div>
添加回答
舉報