在jQuery中使用attr()优于addClass的好处 [英] Benefits of using attr() over addClass in jquery

查看:138
本文介绍了在jQuery中使用attr()优于addClass的好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery中使用attr()代替addClass()有什么好处?

What are the benefits of using attr() instead of using addClass() in jquery?

推荐答案

当您使用attr方法设置任何元素的类时,它将使用您作为方法.

When you use attr method to set the class of any element it will override the existing class name with whatever value you pass as the second argument to attr method.

就像您使用addClass方法向元素中添加任何类一样,它只会添加该类并保留现有的类.如果要添加的类已经存在,则将其忽略.

Where as if you use addClass method to add any class to an element it will just add the class and also retain the existing classes. If the class to add already exists then it will just ignore it.

例如

<div id="div1" class="oldClass"></div>

使用$('#div1').attr('class', 'newClass')会给出

<div id="div1" class="newClass"></div>

在使用$('#div1').addClass('newClass')的情况下会给出

<div id="div1" class="oldClass newClass"></div>

因此,始终建议使用addClass/removeClass使用jQuery处理html元素的类.但最后取决于您的要求何时使用什么.

So it is always adviseable to use addClass/removeClass to manupulate classes of html elements using jQuery. But at the end it depends on your requirement what to use when.

这篇关于在jQuery中使用attr()优于addClass的好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆