Comparing classes of items to execute function(variable variable?)
In Jquery, I want to compare the classes of an h3 and a div. However, I have a lot of these and I can't go through and do case switches because more of these may be added in the future. Here is an example:
<h3 class="one">One</h3>
<h3 cl开发者_高级运维ass="two">Two</h3>
<h3 class="three">Three</h3>
<div class="one">One</div>
<div class="two">Two</div>
<div class="three">Three</div>
On clicking the h3, the div will toggle show/hide. However, as I said, there are a lot of these. Is there any way to say in Jquery that
if h3[class] = div[class] {
//do something
}
without having to state each case of class comparison? Maybe a variable or something?
Given h3
and div
are DOM nodes and only have one class each
if (h3.className === div.className) {
/* runs if both h3 and div have the same class attribute value.
}
For multiple classes I recommend you use ES5 and classlist
if (Array.prototype.every.call(h3.classList, function(v) {
return div.classList.contains(v);
})
) {
/* runs if both h3 and div share the same classes */
}
.classList
, Array.prototype.every
, ES5-shim
精彩评论