我正在寻找一个数组来计算并保持对页面某个区域所做的点击的跟踪;然后,我希望每次点击都能做点什么。例如。)第五次通过mp3触发器点击声音。第六次点击页面震动。
如何编写数组以按点击次数添加不同的事件,为特定点击次数分配内容?
答案 0 :(得分:2)
var clicks = 0;
$('a').click(function() {
switch(++clicks) {
case X:
/* do something */
break;
/* ... */
}
});
或者您可以将函数存储在数组
中var myEvents = [function1, function2, function3];
var clicks = -1;
$('a').click(function() {
clicks++;
if(myEvents[clicks] != undefined) myEvents[clicks]();
});
答案 1 :(得分:1)
这样的事情!
var actions = {
5: 'playMusic',
6: 'shakeDiv'
},
actors = {
doNothing: function() {/*default action; do nothing;*/},
playMusic: function() {
alert('Your are about to here a music now');
/*place code for playing music here*/
},
shakeDiv: function() {
alert('page is about to shake');
/* place shake animation code here*/
}
},
defaultActionName = 'doNothing';//default action name
var clickCount = 0;
$('yourSelectorForThepart').click(function(e) {
clickCount++;
doAction();
});
function doAction() {
var actionName = actions[clickCount] || defaultActionName;
actors[actionName]();
}
是的,您可以合并actions
& actors
。但我更喜欢这种维护方法。可读性。
答案 2 :(得分:1)
http://jsbin.com/izutav/1/edit
只需创建一个事件函数数组:
var a1_Events = [shake, noise, something],
a1_c = 0;
function shake(){
alert('SHAKING!');
}
function noise(){
alert('BZZZZZZZZZZZ!');
}
function something(){
alert('SOMETHING ELSE!');
}
$('#area1').click(function(){
a1_Events[a1_c++ % a1_Events.length]();
});
如果您不希望循环播放事件而不仅仅使用:a1_Events[a1_c++]();
答案 3 :(得分:0)
你可以这样做:
// put your click actions as functions here
var clickEvents = [function1, function2, function3, function4, playMP3, shakePage];
var clicks = 0;
// put your clickable object here
clickableObject.onclick = function(){
clickEvents[clicks]();
clicks++;
}