2015-06-25 50 views
0

我有以下结构::not(.class)无法正常工作?

<div class="container"> 
    <div class="post"> 
     <div class="like liked"></div> 
    </div> 
</div> 

这里是我的JS:

$('.container .post .like:not(.liked)').on('click', function() 
{ 
    // this gets fired even if the element has class "liked" 
}); 

为什么即使元素具有类JS火“喜欢”时,它应该只有火,如果它有类“喜欢”?

+2

似乎工作,看到http://jsfiddle.net/depperm/y07qyh26/ – depperm

+0

@depperm然后我无言以对因为它不适合我。 – user5045769

回答

0

的唯一原因,这将是类liked动态添加。也就是说,处理程序已经在DOM准备好之后注册了。

Not working Demo

所以,当时的事件处理程序注册的股利与like没有liked类。所以这个事件是有效的,并最终点击点击。

使用事件代表来避免这种情况。

$('.container .post').on('click','.like:not(.liked)',function(){ 

}) 

Working Demo

另一种选择是,

$('.container .post .like').on('click', function(){ 
    if(!$(this).hasClass('liked')){ 

    } 
}); 
+0

这个修复了,谢谢! – user5045769

+0

只剩20秒,直到我可以标记为答案。 – user5045769

2

使用jQuery而不是替代:

$('.container .post .like').not('.liked').on('click', function() { 
    // this gets fired even if the element has class "liked" 
}); 
1

用途:

$('.container .post .like').not('.liked').on('click', function() 
{ 
    // this gets fired even if the element has class "liked" 
}); 

或者,

$('.container .post .like :not(".liked")').on('click', function() 
//      ^^^ space between not selector 
{ 
    // this gets fired even if the element has class "liked" 
}); 
0

这是因为你的选择是不加引号。

$('.container .post .like:not(".liked")').on('click', function(){ 
// do stuff 
}); 

you can also use the jQuery .not 

$('.container .post .like').not('.liked').on('click', function(){ 
// do stuff 
}); 

编辑:添加一个codepen.io例如:http://codepen.io/anon/pen/GJOLew