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');
}); 


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

推荐答案

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

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

为了简单起见,您也可以像这样一步一步地执行(注意,将jquery对象分配给var不是必需的,但如果在添加新类之前意外删除了目标类,并通过jquery Select 器(如$('.theClassThatsThereNow'))直接访问dom node ,则会更安全):

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:

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

(假设一个元素的类别为theClassThatsThereNow)

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 ');

Jquery相关问答推荐

逐个交换图像

使用 Ajax 列出数据(仅显示最后的数据)

ASP.NET Core 6 jQuery 验证不起作用

如何使用jQuery删除父元素

jQuery 与 javascript?

扩展 jQuery 插件的最佳方式

如何使用jQuery找到元素顶部的垂直距离(以px为单位)

不使用插件的 jQuery 缓动函数

JavaScript 吸管(告诉鼠标光标下像素的 colored颜色 )

jQuery 中 prop() 和 attr() 的区别以及何时使用 attr() 和 prop()

延迟后运行功能

如何在 jQuery .each() 的每次迭代之间添加暂停?

使用 jQuery 刷新(重新加载)页面一次?

Select 除第一个之外的所有子元素

jQuery ajax 在 asp.net mvc 中上传文件

addClass - 可以在同一个 div 上添加多个类吗?

jQuery闪烁突出显示对div的影响?

如何在 JQuery 中 Select 除单击元素之外的所有类?

JS - 从base64代码中获取图片的宽高

如何使用新的 JSON 数据手动更新数据表