我正在尝试学习jquery,我有一些基本的javascript。
我已经编写了这段代码来切换3个函数,它工作正常
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
</head>
<style type="text/css">
.format1{
background: red;
}
.format2{
background: yellow;
}
.format3{
background: blue;
}
</style>
<div id="div-toggle">Click here to toggle</div>
<script language="javascript">
var click = 0;
$('#div-toggle').toggle(
function(){
var el = $('#div-toggle');
el.addClass('format1');
el.html('No. of clicks: ' + click++);
},
function(){
var el = $('#div-toggle');
el.removeClass('format1');
el.addClass('format2');
el.html('No. of clicks: ' + click++);
},
function(){
var el = $('#div-toggle');
el.removeClass('format2');
el.addClass('format3');
el.html('No. of clicks: ' + click++);
}
);
</script>
</html>
此处如果您看到切换中所有功能的内容相似。如何通过将这些代码移动到单个函数来改进这一点?
答案 0 :(得分:6)
编写一个函数来生成回调:
var click = 0; // keep track of how many times user has clicked
// Generates an event handler that will remove oldClass, add newClass, increment
// click, and update the element text whenever it is called.
function ClassSwapper(oldClass, newClass)
{
return function()
{
$(this)
.removeClass(oldClass)
.addClass(newClass)
.html('No. of clicks: ' + ++click);
};
}
// generate three event handlers for toggle, such that the three
// format classes are cycled.
$('#div-toggle').toggle(
ClassSwapper('format3', 'format1'),
ClassSwapper('format1', 'format2'),
ClassSwapper('format2', 'format3')
);
请注意toggle()
将处理程序从上一个回到第一个,所以您可能希望第一个处理程序删除最后一个添加的类...
由于你要保留一个计数器,你可以完全避免toggle()
,并将计数器,循环的类列表和click
事件处理程序组合起来:
// number of times user has clicked, and also index of *next* class to use
var click = 0;
$("#div-toggle").click(function()
{
// classes to cycle through
var classes = ['format1', 'format2', 'format3'];
// removes previous class, adds new one.
// note that, for brevity, this takes advantage of
// a detail specific to JavaScript arrays: negative indexes are
// interpreted as property names, so the first time this is called,
// removeClass() will be passed the value of classes["-1"] (which will
// return undefined) and will as a result do nothing.
$(this)
.removeClass(classes[(click-1)%classes.length])
.addClass(classes[(click)%classes.length])
.html('No. of clicks: ' + ++click);
});
答案 1 :(得分:1)
我认为你应该通过javascript关闭。
使用javascript闭包你可以将javascript重写为
<script language="javascript">
var click = 0;
$('#div-toggle').toggle(
toggle('format1'),
toggle('format2', 'format1'),
toggle('format3', 'format2')
);
function toggle(add, remove){
return function(){
var el = $('#div-toggle');
if(remove){
el.removeClass(remove);
}
el.addClass(add);
el.html('No. of clicks: ' + click++);
}
}
</script>
我希望这能解决你的问题。
您可以使用其中一些资源来了解闭包
http://www.jibbering.com/faq/faq_notes/closures.html
http://www.javascriptkit.com/javatutors/closures.shtml
http://ejohn.org/apps/learn/#48