2014-07-19 31 views
-1

下面是代碼鏈接http://codepen.io/anon/pen/kzJvl(以下全碼)爲什麼在滿足條件(removeClass)時不會調用jquery(hover)效果?

的代碼應該刪除類的所有實例.gigante

$('.gigante').removeClass('gigante'); 

所以因此懸停效果,其上的所有項目工程沒有.gigante

$civs.hover(function() { 
    $(this).addClass("colorise"); 
}, function() { 
    $(this).removeClass("colorise"); 
}); 

應該對代碼中的所有元素都有效?不是嗎?

然而,第二個div項目似乎仍然有一個類或某事的遺蹟,我不理解

筆的全碼:

的JavaScript:

var $gigante = $('.gigante'); 
var $civs = $(".civ-item:not(.gigante)"); 

// HOVER 
$civs.hover(function() { 
    $(this).addClass("colorise"); 
}, function() { 
    $(this).removeClass("colorise"); 
}); 

// REMOVE CLASS 
$civs.bind('click', function() { 
    $('.gigante').removeClass('gigante'); 
}); 

CSS:

.civ-item{ 
float:left; 
background-color: #2D2D2D; 
width: 238px; 
height: 160px; 
border: 1px solid red; 
margin-bottom: 2px; 
} 
.gigante { 
    width: 478px; 
    height: 600px; 
} 
.colorise { 
    background-color: blue; 
} 

HTML:

<div class="remove"></div> 
    <div id="container" class="clearfix"> 
     <div class="civ-item"></div> 
     <div class="civ-item gigante"></div> 
     <div class="civ-item"></div> 
     <div class="civ-item"></div> 
</div> 
+1

你沒理解,事件處理程序是如何工作的,就必然要選擇相匹配的所有元素**在稍後結合**,去除類的時間不刪除已綁定的事件處理程序。 – adeneo

+0

始終在問題中放入**全部**的相關代碼。例如,在這種情況下,您並未顯示如何填入「$ civs」,這對了解問題至關重要。記住鏈接腐爛,其他服務器可能無法訪問,人們不應該離開網站來幫助你。 –

回答

1

應該對代碼中的所有元素都有效嗎?不是嗎?

不,因爲你$civs變量是之前元素的列表填寫您刪除的類。

你至少有三種選擇:

  1. 事件代表團 - 你在提問中的一個容器上掛鉤事件(理想的東西接近他們,但你可以在最壞的情況下使用document) ,但告訴jQuery你只關心事件,如果它通過匹配選擇器的東西。在你的情況下,你會爲​​你的輸入邏輯掛上mouseenter,爲你的退出邏輯鉤上mouseleave

    var $gigante = $('.gigante'); 
    
    // HOVER 
    $(document) 
        .on("mouseenter", ".civ-item:not(.gigante)", function() { 
        $(this).addClass("colorise"); 
        }) 
        .on("mouseleave", ".civ-item:not(.gigante)", function() { 
        $(this).removeClass("colorise"); 
        }) 
    ; 
    
    // REMOVE CLASS 
    $(".civ-item").bind('click', function() { 
        $('.gigante').removeClass('gigante'); 
    }); 
    
  2. 當您從要素刪除類,重新查詢組新$civs元素的重新綁定您的處理程序:

    function civsHandler() { 
        $('.gigante').removeClass('gigante'); 
        $civs = $(".civ-item:not(.gigante)"); // Of course, there aren't any anymore, 
                  // but I'm allowing for the case where 
                  // you only remove some or something 
        $civs.unbind('click').bind('click', civsHandler); 
    } 
    $civs.bind('click', civsHandler); 
    
  3. 綁定到所有.civ-item元素:

    var $civs = $(".civ-item"); 
    

    ...並檢查何時發生懸停是否有gigante類:

    $civs.hover(function() { 
        if (!$(this).hasClass("gigante")) { 
        $(this).addClass("colorise"); 
        } 
    }, function() { 
        if (!$(this).hasClass("gigante")) { // You may or may not want this check 
        $(this).removeClass("colorise"); 
        } 
    }); 
    
相關問題