jq 获取含类的子集_jQuery获取包含具有特定html值的子元素的元素

I would like to use Jquery to add a class to "li" element that contains a "span" element with a html/val equal to zero.

For Example if my code looks like this:

  • Item 130
  • Item 20
  • Item 320

I want to change it to the following:

  • Item 130
  • Item 20
  • Item 320

In the past I have used code to check elements attribute values, but never their html/val doing something to this effect...

$('li').has('span.num').addClass('disabled');

However in this case that would result in:

  • Item 130
  • Item 20
  • Item 320

Which is obviously not going work... Thanks

解决方案

This should do what you want.

$('li').each(function(){

if( $(this).find('span.num').text() == '0' ) $(this).addClass('disabled')

});

I would have suggested the following:

$('li').has('span.num:contains(0)').addClass('disabled')

But it doesn't work, as it checks if the value exists inside the html — not for an exact match. In this case, each of the span.num elements have a 0 in them, so every li would get the selected class. There doesn't seem to be an :equals() counterpart to the :contains() selector.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值