JavaScript-单击另一个元素后,将元素还原为原始样式 [英] JavaScript - Revert element to original style after clicking another element
问题描述
所以我正在构建一个日历程序,我希望用户能够选择一天.使用< table>
,通过将 className ="NewStyle"
应用于框,在单击时< td>
会突出显示.我希望该单元格在单击另一个单元格后能恢复正常,但它仍保持新样式.
So I'm building a calendar program, and I want the user to be able to select a day. Using a <table>
, the <td>
highlights when clicked by applying className="NewStyle"
to the box. I want that cell to go back to normal after clicking on another cell, but it just remains in its new style.
当另一个单元格被单击时,如何使JS将所有未单击的单元格恢复为正常状态?
How do I make JS revert any non-clicked cell to normal when another cell is clicked?
这是 JSFiddle .感谢您的帮助!
HTML
这些单元格看起来像这样:
The cells look like this:
<td id="td_4" onclick="change(4)">4</td>
<td id="td_5" onclick="change(5)">5</td>
<td id="td_6" onclick="change(6)">6</td>
单击 td_4
将成功更改样式.但是,单击 td_6
也会成功更改样式,但是将 td_4
保留为新样式,而不是还原它.
Clicking td_4
will successfully change the style. But clicking td_6
will also successfully change styles, but leave td_4
in its new style instead of reverting it.
JavaScript
function change(x) {
document.getElementById("td_" + x).className = "selected";
}
推荐答案
只需跟踪单击的元素并将其取消分类即可.小提琴
Just keep track of the element you clicked and unclass it. fiddle
var previousEl
function change(x) {
if (previousEl) previousEl.className = ""
previousEl = document.getElementById("td_" + x)
previousEl.className = "selected"
}
更新:值得一提的另一件事是,您可以利用事件冒泡的优势,以便您的父容器可以侦听事件,并从事件对象中获取clicked元素的ID.更新了小提琴
UPDATE: Another thing worth mentioning is that you can take advantage of event bubbling so that your parent container can listen to events, getting the id of the clicked element from the event object. updated fiddle
var previousEl
function change(event) {
if (previousEl) previousEl.className = "";
previousEl = document.getElementById(event.target.id)
previousEl.className = "selected";
}
,并在您的html中删除所有< td onclick ="change()">
,并将其放置在父项中,并传递事件:
and in your html get rid of all your <td onclick="change()">
and put it on parent, passing event:
<table onclick="change(event)">
这篇关于JavaScript-单击另一个元素后,将元素还原为原始样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!