2014-10-08 299 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()可避免不必要的分配。

相关问题