假设我有以下HTML
<DIV id="root" my-custom-attribute>
<BLOCKQUOTE>
<P id="one">I should not work</P>
</BLOCKQUOTE>
<P id="two">I should work</P>
<SECTION>
<P id="three">I should work</P>
</SECTION>
</DIV>
如果我选择了三个P标签中的一个(例如$('#one')),我可以通过执行以下操作检查它是否为特定类型:
$('#one').is('[my-custom-attribute] > P'); // false
假设我有一组我想说的选择器会使属性“有效”。例如:
var selectors = '[my-custom-attribute] > P, [my-custom-attribute] > SECTION > P';
$('#one').is(selectors); // will return false
$('#two').is(selectors); // will return true
$('#three').is(selectors); // will return true
在这种情况下,我不想说元素是有效的,如果它在blockquote中,但在其他2种情况下,它是有效的。
这个有效选择器列表将大于此,但它们共享的共同特征是我希望选择器以具有my-custom-attribute属性的元素开头。有没有办法以优雅的方式编写我的选择器,我不必用[my-custom-attribute]启动所有选择器?
答案 0 :(得分:1)
尝试
var selectors = $('[my-custom-attribute]').find('> P, > SECTION > P');
$('#one').is(selectors);
$('#two').is(selectors);
$('#three').is(selectors);
演示:Fiddle