我正在尝试学习 jquery,我有一些基本的 javascript. 我已经编写了这段代码来在3个函数之间切换,它运行正常 htmlhead script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"/script/headstyle typ
我已经编写了这段代码来在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>
在这里,如果您看到切换中所有功能的内容相似.如何通过将这些代码移动到单个函数来改进这一点?
编写一个函数来生成回调: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()将处理程序从最后一个返回到第一个,因此您可能希望第一个处理程序删除最后一个添加的类…
由于你要保留一个计数器,你可以完全避免切换(),并组合计数器,循环遍历的类列表,以及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);
});
