2013-01-17 48 views
0

是否有任何方式使用.on()委托事件中的jQuery选择器? 你将如何选择只有直接选择器中的孩子? 以下是一段代码示例:我只想过滤<section>元素的即时<div>子元素,并且要求至少其中一个<p>子元素包含单词«您好»。 在此示例中,只有第二个<div>将被过滤。问题是,其他<div>可以后添加,所以事件必须委派。jQuery筛选器()选择与.on委托事件

的使用.live()方法,使其更简单恕我直言,因为我可以用:

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

但因为它现在已经过时,其更换。对()只允许纯CSS在委托事件中的类似选择器。 有没有人有任何想法如何根据上述2个条件过滤这些元素(直接的孩子& <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:包含(“你好”)不足以作为选择。

$('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; 
    }) 
); 

回答

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

会对股利时,你必须设定的功能

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

     // ... 
     } 
    }) 

这是懒惰的我总是做在我的代码中的条件:它的更好将活动附加到文件和委托; jQuery的工作方式方法更快这种方式+您可以添加元素动态无是否事件的担忧将被触发与否(它将)

$(document).on(... 
+0

“'> div ...''” - 这真的有用吗? –

+0

是的,但重读这个问题后,也许你想要的事件上的编辑... – mikakun

+0

感谢您的快速答案,但正如扬说,它不起作用。 HTTP://的jsfiddle。net/WP7aW/>>鼠标结束时,这两个div都是“背景颜色”。 – rgandoin

2

您可以使用明火的组合子目标的背景下的孩子,即使是在has伪类:

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

但是,建议避免它们(与querySelectorAll不兼容)。考虑(仅一个赤裸裸的组合子,而不是两个):

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

你的第二个过滤器(即有两个以上的孩子与文本格“你好”)是在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)){ 
    ... 
    } 
}) 
+0

谢谢1月,我会去如果条件的解决方案,少说“野”,如你所说;-) – rgandoin

+0

@rgandoin注意,你可以摆脱裸体combinators和其他非国籍完全使用一个明确的条件。无论如何,委托给“文档”似乎是一个好主意。 –