jQuery用另一个类替换一个类

时间:2021-12-23 21:22:16

I have this jQuery and I'm changing styles in it but I've heard that the correct way to do it is to create a separate style and just replace classes with jQuery. Can you explain me how to do it correctly:

我有这个jQuery,我正在改变它的样式,但我听说正确的方法是创建一个单独的样式,只需用jQuery替换类。你能解释一下如何正确地做到这一点:

$('.corpo_buttons_asia').click(function() {           
    $('.info').css('visibility', 'hidden');
    $('.info2').css('visibility', 'visible');
    $(this).css('z-index', '20');
    $(this).css('background-color', 'rgb(23,55,94)');
    $(this).css('color', '#FFF');
    $('.corpo_buttons_global').css('background-color', 'rgb(197,197,197)');
    $('.corpo_buttons_global').css('color', '#383838');         
}); 

$('.corpo_buttons_global').click(function() { 
    $('.info').css('visibility', 'visible');
    $('.info2').css('visibility', 'hidden');
    $(this).css('background-color', 'rgb(23,55,94)');
    $(this).css('color', '#FFF');
    $('.corpo_buttons_asia').css('z-index', '2');
    $('.corpo_buttons_asia').css('background-color', 'rgb(197,197,197)');
    $('.corpo_buttons_asia').css('color', '#383838');
}); 


So instead of using .css() all the time I can create another class and just replace it with jQuery.

所以我不是一直使用.css()而是创建另一个类,而只是用jQuery替换它。

Thanks.

谢谢。

10 个解决方案

#1


93  

To do this efficiently using jQuery, you can chain it like so:

要使用jQuery有效地执行此操作,您可以像这样链接它:

$('.theClassThatsThereNow').addClass('newClassWithYourStyles').removeClass('theClassThatsTherenow');

For simplicities sake, you can also do it step by step like so (note assigning the jquery object to a var isnt necessary, but it feels safer in case you accidentally remove the class you're targeting before adding the new class and are directly accessing the dom node via its jquery selector like $('.theClassThatsThereNow')):

为了简单起见,您也可以像这样一步一步地进行操作(注意将jquery对象分配给var是不必要的,但是如果您在添加新类之前意外删除了您要定位的类并且直接访问它会感觉更安全dom节点通过其jquery选择器,如$('。theClassThatsThereNow')):

var el = $('.theClassThatsThereNow');
el.addClass('newClassWithYourStyles');
el.removeClass('theClassThatsThereNow');

Also (since there is a js tag), if you wanted to do it in vanilla js:

另外(因为有一个js标签),如果你想在vanilla js中这样做:

For modern browsers (See this to see which browsers I'm calling modern)

对于现代浏览器(请参阅此内容以查看我称之为现代的浏览器)

(assuming one element with class theClassThatsThereNow)

(假设一个元素为classClassThatsThereNow)

var el = document.querySelector('.theClassThatsThereNow');
el.classList.remove('theClassThatsThereNow');
el.classList.add('newClassWithYourStyleRules');

Or older browsers:

或旧版浏览器:

var el = document.getElementsByClassName('theClassThatsThereNow');
el.className = el.className.replace(/\s*theClassThatsThereNow\s*/, ' newClassWithYourStyleRules ');

#2


8  

You may use this simple plugin:

你可以使用这个简单的插件:

(function ($) {
    $.fn.replaceClass = function (pFromClass, pToClass) {
        return this.removeClass(pFromClass).addClass(pToClass);
    };
}(jQuery));

Usage:

用法:

$('.divFoo').replaceClass('colored','blackAndWhite');

Before:

之前:

<div class="divFoo colored"></div>

After:

后:

<div class="divFoo blackAndWhite"></div>

Note: you may use various space separated classes.

注意:您可以使用各种空格分隔的类。

#3


3  

Starting with the HTML fragment:

从HTML片段开始:

<div class='helpTop ...

use the javaScript fragment:

使用javaScript片段:

$(...).toggleClass('helpTop').toggleClass('helpBottom');

#4


3  

You can use jQuery methods .hasClass(), .addClass(), and .removeClass() to manipulate which classes are applied to your elements. Just define different classes and add/remove them as necessary.

您可以使用jQuery方法.hasClass(),. addClass()和.removeClass()来操作应用于元素的类。只需定义不同的类,并根据需要添加/删除它们。

#5


2  

Create a class in your CSS file:

在CSS文件中创建一个类:

.active {
  z-index: 20;
  background: rgb(23,55,94)
  color: #fff;
}

Then in your jQuery

然后在你的jQuery中

$(this).addClass("active");

#6


2  

you could have both of them use a "corpo_button" class, or something like that, and then in $(".corpo_button").click(...) just call $(this).toggleClass("corpo_buttons_asia corpo_buttons_global");

你可以让他们两个都使用“corpo_button”类,或类似的东西,然后在$(“。corpo_button”)中。click(...)只需调用$(this).toggleClass(“corpo_buttons_asia corpo_buttons_global”);

#7


2  

In jquery to replace a class with another you can use jqueryUI SwitchClass option

在jquery中用另一个类替换一个类可以使用jqueryUI SwitchClass选项

 $("#YourID").switchClass("old-class-here", "new-class-here"); 

#8


2  

jQuery.fn.replaceClass = function(sSearch, sReplace) {
    return this.each(function() {
        var s = (' ' + this.className + ' ').replace(
            ' ' + sSearch.trim() + ' ',
            ' ' + sReplace.trim() + ' '
        );
        this.className = s.substr(1, s.length - 2);
    });
};

EDIT

This is my solution to replace one class with another (the jQuery way). Actually the other answers don't replace one class with another but add one class and remove another which technically is not the same at all.

这是我用另一个类替换一个类的解决方案(jQuery方式)。实际上,其他答案不会将一个类替换为另一个类,而是添加一个类并删除另一个技术上完全不同的类。

Here is an example:

这是一个例子:

Markup before: <br class="el search-replace"><br class="el dont-search-replace">
js: jQuery('.el').remove('search-replace').add('replaced')
Markup after: <br class="el replaced"><br class="el dont-search-replace replaced">

之前的标记:

js:jQuery('。el')。remove('search-replace')。add('replace ')后标记:


With my solution

用我的解决方案

js: jQuery('.el').replaceClass('search-replace', 'replaced')
Markup after: <br class="el replaced"><br class="el dont-search-replace">

js:jQuery('。el')。replaceClass('search-replace','replacement')后标记:


Imagine a string replace function in whatever language:

想象一下任何语言的字符串替换函数:

Search: "search-replace"
Replace: "replaced"
Subject: "dont-search-replace"
Result: "dont-search-replace"
Result (wrong but actually what the other solutions produce): "dont-search-replace replaced"

搜索:“搜索替换”替换“替换”主题:“不要搜索替换”结果:“不要搜索替换”结果(错误的,但实际上其他的解决方案产生什么):“不要搜索替换替换”


PS If it's for sure that the class to add is not present and the class to remove is present for sure the most simple jQuery solution would be:
jQuery('el').toggleClass('is-present-will-be-removed is-not-present-will-be-added')

PS如果确定要添加的类不存在并且要删除的类确实存在,那么最简单的jQuery解决方案将是:jQuery('el')。toggleClass('is-present-will-removed-removed is is is is -not器存在将待加入')

PPS I'm totally aware that if your selector equals the class to remove the other solutions would work just fine jQuery('.search-replace').removeClass('search-replace').addClass('whatever').
But sometimes you work with more arbitrary collections.

PPS我完全清楚,如果你的选择器等于删除其他解决方案的类,那么jQuery('。search-replace')就会很好.ileveClass('search-replace')。addClass('whatever')。但有时你会使用更多任意的集合。

#9


1  

.removeClass and .addClass. More in http://api.jquery.com

.removeClass和.addClass。更多内容见http://api.jquery.com

#10


1  

You'd need to create a class with CSS -

你需要用CSS创建一个类 -

.greenclass {color:green;}

Then you could add that to elements with

然后你可以添加到元素

$('selector').addClass("green");

and remove it with -

并删除它 -

$('selector').removeClass("green");

#1


93  

To do this efficiently using jQuery, you can chain it like so:

要使用jQuery有效地执行此操作,您可以像这样链接它:

$('.theClassThatsThereNow').addClass('newClassWithYourStyles').removeClass('theClassThatsTherenow');

For simplicities sake, you can also do it step by step like so (note assigning the jquery object to a var isnt necessary, but it feels safer in case you accidentally remove the class you're targeting before adding the new class and are directly accessing the dom node via its jquery selector like $('.theClassThatsThereNow')):

为了简单起见,您也可以像这样一步一步地进行操作(注意将jquery对象分配给var是不必要的,但是如果您在添加新类之前意外删除了您要定位的类并且直接访问它会感觉更安全dom节点通过其jquery选择器,如$('。theClassThatsThereNow')):

var el = $('.theClassThatsThereNow');
el.addClass('newClassWithYourStyles');
el.removeClass('theClassThatsThereNow');

Also (since there is a js tag), if you wanted to do it in vanilla js:

另外(因为有一个js标签),如果你想在vanilla js中这样做:

For modern browsers (See this to see which browsers I'm calling modern)

对于现代浏览器(请参阅此内容以查看我称之为现代的浏览器)

(assuming one element with class theClassThatsThereNow)

(假设一个元素为classClassThatsThereNow)

var el = document.querySelector('.theClassThatsThereNow');
el.classList.remove('theClassThatsThereNow');
el.classList.add('newClassWithYourStyleRules');

Or older browsers:

或旧版浏览器:

var el = document.getElementsByClassName('theClassThatsThereNow');
el.className = el.className.replace(/\s*theClassThatsThereNow\s*/, ' newClassWithYourStyleRules ');

#2


8  

You may use this simple plugin:

你可以使用这个简单的插件:

(function ($) {
    $.fn.replaceClass = function (pFromClass, pToClass) {
        return this.removeClass(pFromClass).addClass(pToClass);
    };
}(jQuery));

Usage:

用法:

$('.divFoo').replaceClass('colored','blackAndWhite');

Before:

之前:

<div class="divFoo colored"></div>

After:

后:

<div class="divFoo blackAndWhite"></div>

Note: you may use various space separated classes.

注意:您可以使用各种空格分隔的类。

#3


3  

Starting with the HTML fragment:

从HTML片段开始:

<div class='helpTop ...

use the javaScript fragment:

使用javaScript片段:

$(...).toggleClass('helpTop').toggleClass('helpBottom');

#4


3  

You can use jQuery methods .hasClass(), .addClass(), and .removeClass() to manipulate which classes are applied to your elements. Just define different classes and add/remove them as necessary.

您可以使用jQuery方法.hasClass(),. addClass()和.removeClass()来操作应用于元素的类。只需定义不同的类,并根据需要添加/删除它们。

#5


2  

Create a class in your CSS file:

在CSS文件中创建一个类:

.active {
  z-index: 20;
  background: rgb(23,55,94)
  color: #fff;
}

Then in your jQuery

然后在你的jQuery中

$(this).addClass("active");

#6


2  

you could have both of them use a "corpo_button" class, or something like that, and then in $(".corpo_button").click(...) just call $(this).toggleClass("corpo_buttons_asia corpo_buttons_global");

你可以让他们两个都使用“corpo_button”类,或类似的东西,然后在$(“。corpo_button”)中。click(...)只需调用$(this).toggleClass(“corpo_buttons_asia corpo_buttons_global”);

#7


2  

In jquery to replace a class with another you can use jqueryUI SwitchClass option

在jquery中用另一个类替换一个类可以使用jqueryUI SwitchClass选项

 $("#YourID").switchClass("old-class-here", "new-class-here"); 

#8


2  

jQuery.fn.replaceClass = function(sSearch, sReplace) {
    return this.each(function() {
        var s = (' ' + this.className + ' ').replace(
            ' ' + sSearch.trim() + ' ',
            ' ' + sReplace.trim() + ' '
        );
        this.className = s.substr(1, s.length - 2);
    });
};

EDIT

This is my solution to replace one class with another (the jQuery way). Actually the other answers don't replace one class with another but add one class and remove another which technically is not the same at all.

这是我用另一个类替换一个类的解决方案(jQuery方式)。实际上,其他答案不会将一个类替换为另一个类,而是添加一个类并删除另一个技术上完全不同的类。

Here is an example:

这是一个例子:

Markup before: <br class="el search-replace"><br class="el dont-search-replace">
js: jQuery('.el').remove('search-replace').add('replaced')
Markup after: <br class="el replaced"><br class="el dont-search-replace replaced">

之前的标记:

js:jQuery('。el')。remove('search-replace')。add('replace ')后标记:


With my solution

用我的解决方案

js: jQuery('.el').replaceClass('search-replace', 'replaced')
Markup after: <br class="el replaced"><br class="el dont-search-replace">

js:jQuery('。el')。replaceClass('search-replace','replacement')后标记:


Imagine a string replace function in whatever language:

想象一下任何语言的字符串替换函数:

Search: "search-replace"
Replace: "replaced"
Subject: "dont-search-replace"
Result: "dont-search-replace"
Result (wrong but actually what the other solutions produce): "dont-search-replace replaced"

搜索:“搜索替换”替换“替换”主题:“不要搜索替换”结果:“不要搜索替换”结果(错误的,但实际上其他的解决方案产生什么):“不要搜索替换替换”


PS If it's for sure that the class to add is not present and the class to remove is present for sure the most simple jQuery solution would be:
jQuery('el').toggleClass('is-present-will-be-removed is-not-present-will-be-added')

PS如果确定要添加的类不存在并且要删除的类确实存在,那么最简单的jQuery解决方案将是:jQuery('el')。toggleClass('is-present-will-removed-removed is is is is -not器存在将待加入')

PPS I'm totally aware that if your selector equals the class to remove the other solutions would work just fine jQuery('.search-replace').removeClass('search-replace').addClass('whatever').
But sometimes you work with more arbitrary collections.

PPS我完全清楚,如果你的选择器等于删除其他解决方案的类,那么jQuery('。search-replace')就会很好.ileveClass('search-replace')。addClass('whatever')。但有时你会使用更多任意的集合。

#9


1  

.removeClass and .addClass. More in http://api.jquery.com

.removeClass和.addClass。更多内容见http://api.jquery.com

#10


1  

You'd need to create a class with CSS -

你需要用CSS创建一个类 -

.greenclass {color:green;}

Then you could add that to elements with

然后你可以添加到元素

$('selector').addClass("green");

and remove it with -

并删除它 -

$('selector').removeClass("green");