javascript - jQuery : How to remove class for all element on click?

标签 javascript jquery addclass

我想知道是否有人可以改进我的代码...我尝试使用 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/

相关文章:

javascript - 未捕获的 TypeError : Property . .. 不是函数 - 页面加载后

jquery 如果元素 id 与其他元素相似则添加类

jquery - 使用 addClass 时的 CSS ID 与 CLASS

javascript - D3 map - 将两个不相交的 svg 多边形路径合并为一个路径

javascript - 如何在 JSON 字符串中包含 Javascript 字符串构造函数?

jquery - 按文本对下拉项目排序

jquery - 替换 jQuery 中的图像扩展名,即时从 .png 到 .gif

javascript - 有没有比使用 addClass/removeClass 更好的方法来做到这一点?

javascript postmessage 不起作用

javascript - 哪些字节的视频数据是指当前播放位置