带有.on委托事件的选择器上的jQuery filter()

时间:2013-01-17 21:06:41

标签: jquery jquery-selectors

有没有办法在委托事件中使用jon选择器和.on()? 你如何在选择器中只选择直接的孩子? 以下是代码示例:我只想过滤<div>元素的直接<section>子项,并要求至少有一个<p>子项包含“hello”一词»。 在该示例中,仅过滤第二个<div>。问题是之后可以添加其他<div>,因此必须委托事件。

使用.live()方法使得imho变得更加简单,就像我可以使用的那样:

$('section > div').filter(function(){return /hello/.test(p) }).live('mouseenter', function(){ ... })

但是由于它现在被弃用,它的替代.on()只允许在委托事件中使用类似CSS的选择器。 有没有人知道如何根据前面提到的2个条件过滤这些元素(直接儿童&amp; <p>包含你好)? 感谢

<section>
    <div>
        <p>abc</p>
        <div>
            <p>def</p>
            <p>hello</p>
        </div>
    </div>
    <div>
        <p>hello world</p>
        <p>test</p>
    </div>
</section>

编辑:我忘了添加我的JS示例,我正在稍微修改条件,以便p:contains('hello')不足以作为选择器。

$('section').on({
    mouseenter: function(){
        $(this).css('background-color','red');
    }
},
    $('div').filter(function(){
        var p = $(this).children('p').filter(function(){
            return /hello/.test($(this).text());
        });
        return p.length > 2;
    })
);

2 个答案:

答案 0 :(得分:3)

$('section').on('mouseenter', '> div > p:contains("hello")', function(){ ... })

要在div上设置事件,您必须在函数

中设置条件
  $('section').on('mouseenter', '> div', function(){ 
      if ($(this).find("> p:contains("hello")").get(0)) {

         // ...
        }
   })

这是懒惰,因为我总是在我的代码中执行:最好将事件附加到文档和委托; jquery以这种方式更快地运行+你可以动态添加元素而不必担心事件是否会被触发(它会)

 $(document).on(...

答案 1 :(得分:2)

你可以使用裸组合子来定位上下文'孩子,即使在has伪类:

$('section').on('mouseenter', '> div:has(> p:contains("hello"))', ...

但是,建议避免使用它们(与querySelectorAll不兼容)。考虑(只有一个裸组合而不是两个):

$(document).on('mouseenter', 'section > div:has( > p:contains("hello"))`, ...

你的第二个过滤器(包含两个以上带有文本“hello”的子项的div)在CSS中有点狂野,但仍然可能:

$('section').on('mouseenter', 'div:has(>'+
  '  p:contains("hello") '+
  '~ p:contains("hello") '+
  '~ p:contains("hello") '+
')', ...

如果所有其他方法都失败了,您可以通过选择器和处理程序内的主过滤器进行预过滤:

$(document).on('mouseenter', 'section > div', function(){
  if($(this).children('p:contains("hello")').length > 2){
    ...
  }
})

即使带有回调的is也可以使用:

function valid (){...}

$(document).on('mouseenter', 'section > div', function(){
  if($(this).is(valid)){
    ...
  }
})