我想知道如何使用jquery或JavaScript来应用一个onclick事件,该事件突出显示所选div并突出显示其他div。。
我有一个动态名称行,用户可以单击查看选定的消息,当用户单击选定的名称时,该名称将用边框突出显示。。。有没有一种简单的方法来实现这种事件,而不必经历以下过程。
function swapme(foo) {
buttons = new Array();
buttons = document.getElementsByTagName('a');
for (i = 0; i < buttons.length; i++) {
if (buttons[i].className === 'active') buttons[i].className = 'inactive';
}
document.getElementById('button' + foo).className = 'active';
}
.inactive {
background: #666;
border: 1px solid #000;
color: #FFF;
padding: 12px
}
.active {
background: #0F0;
border: 1px solid #F00;
color: #F00;
padding: 12px
}
<html>
<head>
</head>
<body>
<p>
<a href="#" onclick="swapme('1'); return false;" class="inactive" id="button1">1</a>
<a href="#" onclick="swapme('2'); return false;" class="inactive" id="button2">2</a>
<a href="#" onclick="swapme('3'); return false;" class="inactive" id="button3">3</a>
<a href="#" onclick="swapme('4'); return false;" class="inactive" id="button4">4</a>
<a href="#" onclick="swapme('5'); return false;" class="inactive" id="button5">5</a>
</p>
</body>
</html>
如果有一个简单的工作,请建议,如在一个切换事件或一个改变。
也可能不需要经过数组循环。。
最佳答案
您可以使用document.querySelectorAll()
移除循环。
您可以实现如下内容:
当点击其中一个名字时
激活当前
从当前活动类中移除活动类
向单击的元素添加活动类
这样就不需要遍历所有按钮。
注意,您可以使用addEventHandler
一次添加所有处理程序,而不是在html中添加onclick
。这将使代码更少耦合,更易于维护。
function swapme(event) {
// Get current active element(s)
document.querySelectorAll('.active')
// Remove active class
.forEach(e => e.className = 'inactive');
// And add the active class to the event target.
event.target.className = 'active';
// Prevent default link hanlding
event.preventDefault();
}
document.querySelectorAll('#container > a')
.forEach(button => button.addEventListener('click', swapme));
.inactive {
background: #666;
border: 1px solid #000;
color: #FFF;
padding: 12px
}
.active {
background: #0F0;
border: 1px solid #F00;
color: #F00;
padding: 12px
}
<html>
<head>
</head>
<body>
<p id="container">
<a href="#" class="inactive" id="button1">1</a>
<a href="#" class="inactive" id="button2">2</a>
<a href="#" class="inactive" id="button3">3</a>
<a href="#" class="inactive" id="button4">4</a>
<a href="#" class="inactive" id="button5">5</a>
</p>
</body>
</html>
关于javascript - 用JavaScript突出显示选定的div,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53177538/