Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

javascript - 检查元素是否包含JavaScript中的类?(Check if an element contains a class in JavaScript?)

Using plain JavaScript (not jQuery), Is there any way to check if an element contains a class?(使用普通的JavaScript(不是jQuery),是否可以检查元素是否包含类?)

Currently, I'm doing this:(目前,我正在这样做:) var test = document.getElementById("test"); var testClass = test.className; switch (testClass) { case "class1": test.innerHTML = "I have class1"; break; case "class2": test.innerHTML = "I have class2"; break; case "class3": test.innerHTML = "I have class3"; break; case "class4": test.innerHTML = "I have class4"; break; default: test.innerHTML = ""; } <div id="test" class="class1"></div> The issue is that if I change the HTML to this...(问题是,如果我将HTML更改为此...) <div id="test" class="class1 class5"></div> ...there's no longer an exact match, so I get the default output of nothing ( "" ).(...不再有完全匹配的内容,因此我得到的默认输出为none( "" )。) But I still want the output to be I have class1 because the <div> still contains the .class1 class.(但是我仍然希望输出为I have class1因为<div>仍然包含 .class1类。)   ask by daGUY translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use element.classList .contains method:(使用element.classList .contains方法:)

element.classList.contains(class); This works on all current browsers and there are polyfills to support older browsers too.(这适用于所有当前浏览器,并且也有polyfill支持较旧的浏览器。) Alternatively , if you work with older browsers and don't want to use polyfills to fix them, using indexOf is correct, but you have to tweak it a little:(另外 ,如果您使用较旧的浏览器,并且不想使用polyfill对其进行修复,则使用indexOf是正确的,但是您需要对其进行一些调整:) function hasClass(element, className) { return (' ' + element.className + ' ').indexOf(' ' + className+ ' ') > -1; } Otherwise you will also get true if the class you are looking for is part of another class name.(否则,如果您要查找的类是另一个类名的一部分,那么您也将获得true 。) DEMO(演示) jQuery uses a similar (if not the same) method.(jQuery使用类似(如果不相同)的方法。) Applied to the example:(应用于示例:) As this does not work together with the switch statement, you could achieve the same effect with this code:(由于这不能与switch语句一起使用,因此可以使用以下代码实现相同的效果:) var test = document.getElementById("test"), classes = ['class1', 'class2', 'class3', 'class4']; test.innerHTML = ""; for(var i = 0, j = classes.length; i < j; i++) { if(hasClass(test, classes[i])) { test.innerHTML = "I have " + classes[i]; break; } } It's also less redundant ;)(它也较少冗余;))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...