2 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
您正在使用.querySelector()
它返回文檔中與提供的選擇器匹配的第一個(gè)元素。
要獲取多個(gè)元素,您需要使用.querySelectorAll()
它將返回與選擇器匹配的元素的靜態(tài)NodeList。此時(shí),您需要循環(huán)遍歷 NodeList 并操作類。
但是,由于您嘗試定位事件調(diào)用元素,我認(rèn)為您可以通過引用該元素來簡化它。
function?toggleColor(el,?e)?{ ????el.classList.toggle('disable'); ????el.classList.toggle('active'); }
并將您的onclick
處理程序更改為onclick="toggleColor(this,event);"
這是一個(gè)快速片段:
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貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超8個(gè)贊
為什么會(huì)發(fā)生這種情況?
由于有多個(gè)具有 類的元素heart
,因此它不知道要在哪個(gè)元素上執(zhí)行腳本!這就像一個(gè)老師試圖給鮑勃打電話,而班級(jí)里有 5 個(gè)叫鮑勃的人。
我們?cè)撊绾谓鉀Q這個(gè)問題?
onclick
您可以通過在腳本中提供元素的引用來更改 中的函數(shù),如下所示: onclick="myFunction(this)"
?,F(xiàn)在,在 javascript 中,您可以對(duì)元素執(zhí)行任何您需要的操作。
嘗試一下!運(yùn)行下面的例子!
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>
添加回答
舉報(bào)