2015-06-25 51 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