使用javascript从元素中删除类名 [英] Remove classname from element with javascript

查看:98
本文介绍了使用javascript从元素中删除类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从另一个堆栈溢出问题中找到了以下正则表达式:更改元素的类使用JavaScript

I found the following regex from another Stack Overflow question: Change an element's class with JavaScript

在我的脚本中成功使用了它,但是在另一个脚本中似乎失败了.

And have used it in part of my script with success, however in another it seems to be failing.

我在jsFiddle上放了一个非常简单的测试用例,但它也失败了:

I threw together a very minimalist test case on jsFiddle, and it is also failing:

http://jsfiddle.net/ew47Y/1/

HTML:

<div class="foo" id="foo">
    hello
</div>​

JS:

$(document).ready(function(){
     foo = document.getElementById('foo');
     foo.className += ' bar foobar';
     alert(foo.className);
     foo.className.replace( /(?:^|\s)bar(?!\S)/ , '' )
     alert(foo.className);
})​

推荐答案

这是因为 replace 并没有真正修改您调用它的字符串.而是返回一个新字符串.所以:

That's because replace doesn't actually modify the string you call it on; rather, it returns a new string. So:

     foo.className = foo.className.replace( /(?:^|\s)bar(?!\S)/ , '' )

(顺便说一句,您实际上不需要在原始JavaScript中执行此操作,因为jQuery对象提供了 removeClass 方法:

(By the way, you don't actually need to do this in raw JavaScript, since jQuery objects offer a removeClass method: http://api.jquery.com/removeClass/. So you could write:

     $('#foo').removeClass('bar');

或:

     $(foo).removeClass('bar');

)

这篇关于使用javascript从元素中删除类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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