我试图减少一些代码,基本上下面的点击事件被使用了10次,id为#topNavA - #topNavJ,只有2个事件发生了变化。任何人都可以建议我如何为每次点击回收此代码?我已添加评论中的行将从点击事件更改为点击事件但其余部分保持不变?欢迎所有建议。
$('#topNavA').click(function() {
$footerPush.hide();
$allMultipleElements.hide();
$('#section, #placement, .mobileControls').show(); // This line will change with different selectors
$('.mobileControls h1').replaceWith('<h1>Mobilizing Mobile, AL</h1>'); // This line will change with a different header 1
$('.mobileControls h2').replaceWith('<h2>Overview</h2>'); // This line will change with a different header 2
$('.menuTitle').removeClass('active');
$('.lightbox').remove();
$('#nav li > a').removeClass('active');
$('#nav li span a').css({
'color': '#8F8F8F'
});
$('#topNav').addClass('active');
$(this).css({
'color': '#e8af20'
});
});
由于 凯尔
答案 0 :(得分:2)
一种选择是使用data
。您可以在存储变量数据的元素上有3个data-
属性。像这样:
<a href="..." id="topNavA" class="topNavLink" data-selector="#section, #placement, .mobileControls">something</a>
$(".topNavLink").click(function(){
var selector = $(this).data("selector");
$(selector).dosomething();
});
该技术的例子:http://jsfiddle.net/mPQfJ/1/
答案 1 :(得分:1)
我倾向于用一个创建处理程序的函数解决这个问题,这是一个处理程序工厂。外部函数的参数在处理程序的闭包中使用:
function getClickHandler(selectors, header1, header2) {
return function() {
// snip
$(selectors).show();
$(header1).replaceWith('<h1>Mobilizing Mobile, AL</h1>');
$(header2).replaceWith('<h2>Overview</h2>');
// snip
}
}
然后,您可以通过使用特定于该情况的参数调用hander工厂来分配处理程序:
$('#topNavA').click(getClickHandler(
'#section, #placement, .mobileControls',
'.mobileControls h1',
'.mobileControls h2'
));
答案 2 :(得分:1)
不是一个完整的答案,但希望是一个很好的起点:
您应该使用.live()甚至更好的.delegate(),而不是使用.click()。委派一个祖先元素来监听符合您标准的选择器的点击次数:
$('#wrapper').delegate('[id*=topNav]', 'click', function() {
// do stuff on click
})
#wrapper是包含所有topNavX元素的任何祖先(您不必使用ID选择器)。对于包含字符串“topNav”的任何ID,[id * = topNav]将进行字符串匹配。