jQuery确定匹配的类是否具有给定的id [英] jQuery Determine if a matched class has a given id

查看:67
本文介绍了jQuery确定匹配的类是否具有给定的id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是jQuery具有与以下语句等效的ID?

What is jQuery has id equivalent of the following statement?

$('#mydiv').hasClass('foo')

因此您可以提供一个类名,并检查它是否包含提供的ID.

so you could give a class name and check that it contains a supplied id.

类似:

$('.mydiv').hasId('foo')

推荐答案

您可以通过组合多个选择器.例如,我们可以定位具有给定id的所有元素,这些元素也具有特定的类:

You can bake that logic into the selector by combining multiple selectors. For instance, we could target all elements with a given id, that also have a particular class:

$("#foo.bar"); // Matches <div id="foo" class="bar">

这看起来应该类似于您在CSS中编写的内容.请注意,它不适用于所有#foo元素(尽管应该只有一个),也不适用于所有.bar元素(尽管可能有很多).它将仅引用同时符合这两个属性的元素.

This should look similar to something you'd write in CSS. Note that it won't apply to all #foo elements (though there should only be one), and it won't apply to all .bar elements (though there may be many). It will only reference elements that qualify on both attributes.

jQuery还有一个很棒的 .is方法,可让您确定元素是否具有一定的品质.您可以针对字符串选择器,HTML元素或另一个jQuery对象测试jQuery集合.在这种情况下,我们将仅针对字符串选择器进行检查:

jQuery also has a great .is method that lets your determine whether an element has certain qualities. You can test a jQuery collection against a string selector, an HTML Element, or another jQuery object. In this case, we'll just check it against a string selector:

$(".bar:first").is("#foo"); // TRUE if first '.bar' in document is also '#foo'

这篇关于jQuery确定匹配的类是否具有给定的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆