jQuery选择器忽略指定的元素

jQuery selector to ignore specified element

本文关键字:元素 选择器 jQuery      更新时间:2023-09-26

考虑这个DOM:

<div id="div1">
  <div class="no-select-inside">
    <p>Don't select me</p>
  </div>
  <div>
    <p>Select me</p>
    <div><p>Select me too</p></div>
  </div>
  <div>
    <p>Select me</p>
    <div><p>Select me too</p></div>
  </div>
  <footer class="no-select-inside">
    <p>Don't select me</p>
    <div><p>Not me</p></div>
  </footer>
  <section>
    <p>Select me</p>
    <div><p>Select me too</p></div>
  </section>
</div>

我想要一个快速可靠jquery(或裸DOM)选择器来选择那些不在类中的p标记

一切都是动态的,但我可以为不可选的DOM元素分配一个属性。

编辑

真正的测试用例不是一个类选择器(可能是一个复杂的属性选择器,…)

所有东西都是动态的,可能嵌套得太深(在no-select-inside下的DOM树下有100个p,它有一个no-select-inside父级,有了所有答案,即使选择了这些元素)

我缓存了所有的no-select-inside(Backbone的$el,为了提高性能,可以缓存在数组中),但真正的问题是快速选择这些元素(chrome中20ms太慢了!)。

通用解决方案是从具有.no-select-inside祖先的解决方案中选择filter,例如:

$("p")
    .filter(function() { return !$(this).closest(".no-select-inside").length;})
    // and now do what needs to be done

这应该是相当有效的,因为它只对整个文档进行一次检查。

尝试使用.not()或:not()过滤掉no-select-inside 中的p元素

$('#div1 p').not('.no-select-inside p')
$('#div1 p:not(.no-select-inside p)')

试试这个:

$('div:not(.no-select-inside) p')
You can use .not as the working example is here 
$(document).ready(function(){
     var abc = $('#div1').find("p").not('.no-select-inside p');
     $(abc).each(function(e){
        alert($(this).html());
     }); 
 });

http://jsfiddle.net/8F7Kc/14/