下面的代码:为什么我的方法执行两次?
$(document).ready(function() {
$('.category').click(function(){
$("#category-menu").modal();
$("#category-menu").css({'display' : 'block'});
$('.single-category').click(function(){
$('.category-link').fadeOut('slow', 'linear', fadeInCategory($(this)));
/*the line above some how gets called again*/
});
});
$('.mp-back').click(function(){
$('.category-link').css('display', 'none');
var testing = $(this).closest('.mp-level');
testing.css('display', 'none'); /*after this line */
});
});
function fadeInCategory(category){
category.find('.mp-level').fadeIn('slow');
category.find('ul').fadeIn('slow');
}
function back2allCategories(){
$('.category-link').css('display', 'block');
}
当$('.single-category')
点击我淡出了一堆的HTML,并在短短这个孩子褪色。
mp-back
应该回迁,所以我淡出(或设置display:none
作为一个属性)
然而,一旦$('.mp-back').click(function(){
已经执行完毕,这条线:
$('.category-link').fadeOut('slow', 'linear', fadeInCategory($(this)));
不知怎的,它再次被执行,我可以不知道为什么。
(我知道这是通过在谷歌Chrome控制台中的折点发生)
但是我无法真正弄清楚为什么。
为什么$('.category-link').fadeOut('slow', 'linear', fadeInCategory($(this)));
被重新调用?
你应该几乎从不调用里面绑定另一个事件处理函数的事件处理函数。每次你点击'.category'你为'.single-category'绑定一个额外的点击处理器,所以你最终得到了多个处理器。 – Barmar
嗯..这是有道理的...是这个问题,还是只是良好的做法? – brendosthoughts
这就是问题所在。 –