2013-08-25 102 views
2

當我點擊一個div內的子元素('butMedWhite'類) - jquery認爲我點擊父元素('.alternative') - 即使當我在控制檯內轉儲'this'時,它說我點擊了'替代'類(請參閱下面的代碼) - 而不是'butMedWhite'類 - 有沒有人有任何想法爲什麼? 下面是HTML:jquery點擊 - 認爲其父元素,而不是孩子

<div class="alternative _activeCategory"> 
    <div class="alternative_inner"></div> 
    <div class="expandable" style="display: block;"> 
     <div class=" criteriaContainer"> 
      <a class="butMedWhite altCreator">add rule</a> 
     </div> 
    </div> 
</div> 

,這裏是jQuery的:

$('.altExpander').on('click', '.alternative', function(e) { 
        console.log(this); 
        if(!$(this).hasClass('_activeCategory')){ 
         expandCategory($(this)); 
        }else{ 
         closeCategory(); 
        } 
       }); 

感謝您的幫助!

+0

點擊是定義爲容器類替代 –

+0

是的,這是因爲我想在用戶點擊'替代'時以及當他們點擊子元素時發生某些事情 - 對不起,我應該把它放在問題中! – matt

回答

2

jQuery爲您的回調提供了作爲上下文綁定事件處理程序的元素,就像本機DOM函數一樣。

如果你想點擊的元素代替,不使用thise.target

$('.altExpander').on('click', '.alternative', function(e) { 
    var clicked = $(e.target); 
    console.log(clicked); 
    if(!clicked.hasClass('_activeCategory')){ 
      expandCategory(clicked); 
    }else{ 
      closeCategory(); 
    } 
}); 
0

那是因爲你的選擇是在這一行 「.alternative」:

$('.altExpander').on('click', '.alternative', function(e) 

如果你想this要成爲錨標記,您需要使用

$('.altExpander').on('click', '.alternative a', function(e) 
相關問題