what is the right way to determine if an object has one class OR another one? The following is appearantly wrong..
if ($('#menu-item-49').hasClass('current-menu-item' || 'current-menu-parent') ) {
$('开发者_Go百科ul.sub-menu ').css('display', 'block');
}
Thanks!
You could use is
instead?
if ($('#menu-item-49').is('.current-menu-item, .current-menu-parent')) {
$('ul.sub-menu ').css('display', 'block');
}
Check the current matched set of elements against a selector and return true if at least one of these elements matches the selector.
Beats having to use multiple hasClass
queries, which is the alternative:
if ($('#menu-item-49').hasClass('current-menu-item') ||
$('#menu-item-49').hasClass('current-menu-parent')) {
$('ul.sub-menu ').css('display', 'block');
}
You cannot use the ||
(or) operator within hasClass
. Try this:
if ($('#menu-item-49').hasClass('current-menu-item') ||
$('#menu-item-49').hasClass('current-menu-parent')) {
$('ul.sub-menu ').css('display', 'block');
}
Or you can do this if that's too verbose:
var $menuItem = $('#menu-item-49');
if ($menuItem.hasClass('current-menu-item') ||
$menuItem.hasClass('current-menu-parent')) {
$('ul.sub-menu ').css('display', 'block');
}
Or even better:
var $menuItem = $('#menu-item-49');
if ($menuItem.is('.current-menu-item, .current-menu-parent')) {
$('ul.sub-menu ').css('display', 'block');
}
if ($('#menu-item-49').hasClass('current-menu-item') || $('#menu-item-49').hasClass('current-menu-parent') ) {
$('ul.sub-menu ').css('display', 'block');
}
Have you tried the following?
You can also use .is()
to check for any class beginning with current-menu-
by using:
if ( $('#menu-item-49').is('[class]^="current-menu-"') ) {
//49 is the current menu!
}
More attribute selectors like ^=
may be found here.
The following is what you've in mind:
var menuItem49 = $('#menu-item-49');
if (menuItem49.hasClass('current-menu-item') || menuItem49.hasClass('current-menu-parent')) {
// ...
}
So close!
Try:
if ($('#menu-item-49').hasClass('current-menu-item') || $('#menu-item-49').hasClass('current-menu-parent') ) {
$('ul.sub-menu ').css('display', 'block');
}
Do it like this instead, separating it in two bits:
if ($('#menu-item-49').hasClass('current-menu-item') || $('#menu-item-49').hasClass('current-menu-parent') ){
$('ul.sub-menu ').css('display', 'block');
}
Hope this helps you
精彩评论