简体   繁体   English

jQuery-如何检查跨度是否有一个类,如果不存在则添加一个类

[英]JQuery - How to check if a span has a class and add a class if one doesnt exist

I need help with some jquery code to check if a span has a class. 我需要一些jquery代码的帮助,以检查span是否具有一个类。 If it doesn't have a class then add class customtab to this span. 如果它没有类,则将class customtab添加到该范围。 How can I do this in jquery? 如何在jquery中做到这一点?

Here's example html menu. 这是html菜单示例。

<div class="menu">
    <ul>
        <li><a class="user_menu_link" href="#"><span class="menu1">Menu Item 1</span></a><li>
        <li><a class="user_menu_link" href="#"><span class="menu2">Menu Item 2</span></a></li>
        <li><a class="user_menu_link" href="#"><span class="menu3">Menu Item 3</span></a></li>
        <li><a class="user_menu_link" href="#"><span class="menu4">Menu Item 4</span></a></li>
    <li><a href="#"><span>Menu Item 5</span></a></li>
    </ul>
</div>

Here's the code I'm trying to use but doesn't work. 这是我要使用的代码,但是不起作用。

$('ul a').each(function() {
  if ($(this).attr('class') == "") {
    $(this).find('span').addClass("customtab");
  }
});

I was able to use this code to make it work. 我能够使用此代码使其工作。

$('ul a').each(function() {
  if ($(this).attr('class') === undefined) {
    $(this).find('span').addClass("customtab");
  }
});

What class are you checking for and when, eg on click, when the page is loaded, hover, etc. 您要检查什么类,以及何时检查(例如,单击时,页面何时加载,悬停等)。

To check, there is a hasClass method: 要检查,有一个hasClass方法:

// $(this) being the element you are checking for the class
// this could be inside a click function for example
if ($(this).hasClass('menu1')) {
    $(this).addClass('customtab');
}

Update 更新资料

To check for no class attribute, try this: 要检查是否没有class属性,请尝试以下操作:

if ($(this).attr('class') === undefined) {
    $(this).addClass('customtab');
}

If you don't know what $(this) is then you can find the element by looping through the elements: 如果您不知道$(this)是什么,则可以通过遍历元素来查找元素:

$('li a.user_menu_link span').each(function() {
    if ($(this).attr('class') === undefined) {
        $(this).addClass('customtab');
    }
});

http://jsfiddle.net/992g694f/ http://jsfiddle.net/992g694f/

Fiddle with fixed HTML - http://jsfiddle.net/992g694f/1/ 带有固定HTML的小提琴-http: //jsfiddle.net/992g694f/1/

Update 2 更新2

$('ul a').each(function() { 
    if($(this).attr('class') === undefined){    
        $(this).find('span').addClass("customtab"); 
    }
});

Try : 尝试:

$(".menu a span").filter(function() {
    return this.className == '';
}).addClass('customtab');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM