2014-10-08 296 views
0

此代碼適用於所有而不是在按下按鈕的特定元素..點擊按鈕,隱藏元素 「兄弟」,並顯示另一個

HTML:

<div id="ProductsIndex"> 
    <div class="product"> 
     <div class="product-detail"></div> 
     <div class="prod-box"></div> 
     <a class="btn-detail" href=""> <i class="fa fa-times"></i> </a> 
    </div> 

</div> 

的jQuery:

$('#ProductsIndex .product .btn-detail').click(function(e) { 
    e.preventDefault(); 
    $('#ProductsIndex .product .prod-box').hide('slow'); 
    $('#ProductsIndex .product .product-detail').show('slow'); 

    $('#ProductsIndex .product .product-detail .fa-times').click(function(e) { 
     $('#ProductsIndex .product .product-detail').hide('slow'); 
     $('#ProductsIndex .product .prod-box').show('slow'); 
    }); 
}); 

這適用於所有元素,但當按下按鈕時我需要特定的元素。

+0

你是什麼意思*「適用於所有元素」*?其餘的在哪裏? – 2014-10-08 09:59:20

回答

1

您不應該在事件處理程序中綁定事件。

使用

$('.product .btn-detail').click(function(e) { 
    e.preventDefault(); 
    var parent = $(this).closest(".product"); 
    parent.find(".prod-box'").hide('slow'); 
    parent.find(".product-detail").show('slow'); 
}); 

$('.product .fa-times').click(function(e) { 
    var parent = $(this).closest(".product"); 
    parent.find(".prod-box'").show('slow'); 
    parent.find(".product-detail").hide('slow'); 
}); 
+0

+1這是做這件事的正確方法。在另一個事件處理程序中註冊一個事件是最差的編碼練習。 – 2014-10-08 10:02:20

+0

非常感謝!解決! – Sayoko 2014-10-08 10:11:33

0

首先,不要窩在另一個裏面點擊處理程序的附件,否則內側安裝將被重複做,每次外處理火災。其次,你可以利用jQuery的.closest().find()遍歷DOM,點擊節點作爲初始參考點。

$('#ProductsIndex .product .btn-detail').on('click', function (e) { 
    e.preventDefault(); 
    $(this).closest("#ProductsIndex") 
     .find(".prod-box").hide('slow').end() 
     .find(".product-detail").show('slow'); 

}); 
$('#ProductsIndex .product .product-detail .fa-times').on('click', function (e) { 
    $(this).closest("#ProductsIndex") 
     .find(".product-detail").hide('slow').end() 
     .find(".prod-box").show('slow'); 
}); 

注意:明智地使用.end()可避免不必要的分配。

相關問題