我想知道是否有人可以改进我的代码...我尝试使用 jQuery 在元素上应用一个类,我们只需单击并在其他元素上禁用该类。
您将在我的代码中看到,我正在尝试在我刚刚单击的元素上应用一个类,并删除其他元素上的所有类。
但目前,我正在以“简单且漫长的方式”进行操作,正如您在 $("choice1-1").click(function() 中看到的那样
有人可以帮我编写一个可以检测所有其他 ID 的代码吗?
这是我目前的代码
$(document).ready(function()
{
$('#stick-question-1').mouseenter(function()
{
$('#stick-choices-1').show();
});
$('#stick-choices-1').mouseleave(function()
{
$('#stick-question-1').show();
$('#stick-choices-1').hide();
});
$("choice1-1").click(function()
{
$(this).addClass('hover-etat');
$("#choice1-2").removeClass('hover-etat');
$("#choice1-3").removeClass('hover-etat');
$("#choice1-4").removeClass('hover-etat');
});
});
我的 HTML 是这样的
<div id="stick-choices-1" class="stick-choices">
<a href="#" onclick="displayChoice1('Under 3\'9'); return false;" id="choice1-1">Under 3'9</a>
<a href="#" onclick="displayChoice1('4\' to 5\'2'); return false;" id="choice1-2">4' to 5'2</a>
<a href="#" onclick="displayChoice1('5\'3 to 5\'7'); return false;" id="choice1-3">5'3 to 5'7</a>
<a href="#" onclick="displayChoice1('5\'8 and more'); return false;" id="choice1-4">5'8 and more</a>
</div>
最佳答案
只需使用:
$("#stick-choices-1 a").click(
function(e) {
e.preventDefault();
$('.hover-etat').removeClass('hover-etat');
$(this).addClass('hover-etat');
});
我更改了您的初始选择器,以便 click
单击 #stick-choices-1
中的任何链接即可触发事件div
元素,它阻止单击链接的默认操作(假设您希望停止默认操作),删除 hover-etat
任何具有该类的元素中的 class,然后将该类名应用于 this
元素。
不过,限制 jQuery 使用 hover-etat
搜索元素的范围可能是有意义的。类,到同一个 #stick-choices-1
中的那些元素元素,而不是整个文档:
$("#stick-choices-1 a").click(
function(e) {
e.preventDefault();
$('#stick-choices-1 .hover-etat').removeClass('hover-etat');
$(this).addClass('hover-etat');
});
或者:
$("#stick-choices-1 a").click(
function(e) {
e.preventDefault();
$(this).siblings('.hover-etat').removeClass('hover-etat');
$(this).addClass('hover-etat');
});
关于javascript - jQuery : How to remove class for all element on click?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10232478/