jQuery用另一个类替换一个类 [英] jQuery replace one class with another
问题描述
我有这个jQuery,我正在改变它的样式,但我听说正确的方法是创建一个单独的样式,只需用jQuery替换类。你能解释一下如何正确地做到这一点:
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:
$('.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');
});
所以不要使用 .css()我总是可以创建另一个类,只需用jQuery替换它。
So instead of using .css() all the time I can create another class and just replace it with jQuery.
推荐答案
要有效地使用它jQuery,你可以像这样链接它:
$('.theClassThatsThereNow').addClass('newClassWithYourStyles').removeClass('theClassThatsTherenow');
为了简单起见,你也可以像这样一步一步地做(注意将jquery对象分配给var是不必要的,但是如果您在添加新类之前意外删除了您要定位的类并且通过其jquery选择器直接访问dom节点(如 $('。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')
):
var el = $('.theClassThatsThereNow');
el.addClass('newClassWithYourStyles');
el.removeClass('theClassThatsThereNow');
另外(因为有一个js标签),如果你想在香草里做js:
对于现代浏览器(看到这个,看看我称之为现代的浏览器)
(假设一个元素的类 theClassThatsThereNow
)
var el = document.querySelector('.theClassThatsThereNow');
el.classList.remove('theClassThatsThereNow');
el.classList.add('newClassWithYourStyleRules');
或旧浏览器:
var el = document.getElementsByClassName('theClassThatsThereNow');
el.className = el.className.replace(/\s*theClassThatsThereNow\s*/, ' newClassWithYourStyleRules ');
这篇关于jQuery用另一个类替换一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!