【问题标题】:What's the most efficient way to return to previous state when another link is clicked outside the element? (jQuery)当在元素外部单击另一个链接时,返回先前状态的最有效方法是什么? (jQuery)
【发布时间】:2011-09-15 16:40:40
【问题描述】:

我有一个链接,点击后会改变它的状态:

$('.last_link').bind("click", function() {
     $(this).css({"color" : "#BBB", "cursor" : "default"});
});

但是,如果我单击该链接集中的另一个链接,它仍会保留该状态。当我点击另一个链接时,我希望链接返回到之前的状态。

当我单击其他链接时,不是重新设置 .last-link 的先前状态,有没有更好、更有效的方法来恢复此选择器的原始状态?

(编辑:假设我在该函数中除了 .css() 之外还有其他方法,就像我有一个方法链一样。)

【问题讨论】:

    标签: javascript jquery css-selectors


    【解决方案1】:
    .high-state {
        color: #BBB;
        cursor: default;
    }
    
    a {
       color: blue;
       cursor: pointer;
    }
    
    $("a").click(function() {
        $(".high-state").removeClass('high-state');
        $(this).addClass('high-state');
    });
    

    http://jsfiddle.net/majidf/4r6XN/

    【讨论】:

    • here 您可以观看此操作。我只是设置示例太慢了
    【解决方案2】:

    假设您已经使用 css 而不是 style 属性设置了样式,您可以这样做 $('.last_link').removeAttr('style')

    这是因为调用 .css() 设置了 style 属性的值,所以如果你删除它,状态将被恢复。

    http://jsfiddle.net/jQ2xw/

    【讨论】:

    • 是的,我认为这是一种更短的方式。但是,我编辑了我的问题以包含一系列方法,而不仅仅是一个方法。
    • @catandmouse 我不确定这到底有什么不同?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    相关资源
    最近更新 更多