简体   繁体   English

将类添加到没有类的元素-jQuery

[英]Add class to element that doesn't have class - jQuery

In the table below only one td has class, another doesn't have class like: 在下table中,只有一个td具有类,另一个不具有类似类:

<table id="bow-me">
  <tr class="row-me">
    <td class="show-me">Pet is Great</td>
    <td>Pete is Greate</td>
  </tr>
</table>

I tried something like: 我尝试了类似的东西:

if(!$("#bow-me tr td").hasClass("show-me")) {
  $(this).addClass("know-me");
}

But this doesn't add the class know-me in my second td here. 但这并没有在我的第二个td添加class 知识

I have attached the JSFiddle here 我在这里附上了JSFiddle

If I want to add Class to the second td only then how do I do? 如果我只想将Class添加到第二个td ,该怎么办?

Try attribute selector and :not() to get the <td> without any class 尝试使用属性选择器和:not()获得<td>而不带任何类

$('#bow-me tr td:not([class])').addClass('know-me');

Or if you want to specify which <td> like first or second, use :eq() 或者,如果要指定第一个或第二个<td> ,请使用:eq()

$('#bow-me tr td:eq(1)').addClass('know-me');

Doc reference 文件参考

  1. :not() :不()
  2. Attribute selectors 属性选择器
  3. .eq() .eq()

You can use :eq() selector: 您可以使用:eq()选择器:

$('#bow-me tr.row-me td:eq(1)').addClass('know-me');

Updated Fiddle 更新小提琴

or .eq() .eq()

$('#bow-me tr.row-me td').eq(1).addClass('know-me');

Updated Fiddle 更新小提琴

the reason your code doesn't work is because 您的代码不起作用的原因是

  1. There are multiple td 's found with your selector 您的选择器找到多个td

    $("#bow-me tr td")

  2. You can't use the $(this) as a selector inside your if conditional statement. 您不能将$(this)用作if条件语句中的选择器。 it has no valid reference as is. 它没有有效的参考。

Solution: you can cycle through the matched elements via each() function and then set up your conditional to check each one of the elements found - $(this) would work in this case 解决方案:您可以通过each()函数循环匹配的元素,然后设置条件以检查找到的每个元素- $(this)在这种情况下可以工作

$("#bow-me tr td").each(function() {
  if(! $(this).hasClass("show-me")) {
    $(this).addClass("know-me");
  }
});

check out the jsFiddle here 这里查看jsFiddle

I gave this answer as an explaination as to why your approach does not work. 我给出了这个答案,以解释您的方法为何行不通。 I prefer Anton's approach that uses the :not() pseudo selector. 我更喜欢使用:not()伪选择器的安东方法。

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

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