2 回答
TA贡献2021条经验 获得超8个赞
为要突出显示的所有元素添加一个类并对其进行迭代。在我的示例中,我word为所有跨度添加了类:
<table style="width:80%" border ="1">
<tr>
<td width="70%">
The book is
<span class="word blue_3">smart,</span>
<span class="word blue_5">handsome,</span> and <span class="word blue_4">funny.</span><br>
The book is <span class="word red_3">terrible <br></span>
The book was <span class="word blue_1">good., </span> <br>
Today <span class="word red_4">SUX</span>!, <br>
Today only kinda <span class="word red_4">sux!</span> <br>
But I'll get by, <span class="word blue_3">lol,</span> <br>
</td>
<td>
<button id="button">Highlight</button>
</td>
</tr>
</table>
以这种方式调整JS:
document.getElementById("button").addEventListener("click", function() {
Array.from(document.getElementsByClassName('word')).forEach(
span => span.classList.toggle("highlight")
);
this.innerHTML = (this.innerHTML === "Highlight") ? "Unhighlight" : "Highlight";
})
https://jsfiddle.net/9gdqunfo/
TA贡献1829条经验 获得超13个赞
这是工作代码,
document.getElementById("button").addEventListener("click", function() {
[].forEach.call(document.querySelectorAll("span"), p => {
p.classList.toggle("highlight");
});
this.innerHTML = (this.innerHTML === "Highlight") ? "Unhighlight" : "Highlight";
})
https://codepen.io/pgurav/pen/eYYovmN
如果对你有帮助就点个赞
添加回答
举报