简体   繁体   English

每次点击同一元素的事件不同

[英]Different event for each click on same element

How Do I fire a new event for each click on a button. 如何为每次单击按钮触发新事件。 And how do I bring it in a loop, so after "click 3" it starts again with "click 1". 以及如何将其循环播放,因此在“单击3”之后,它再次从“单击1”开始。

$('button').click(function () {

     //click 1
     cameraTween( camera.position, 1, 1, 1 );

     //click 2
     cameraTween( camera.position, 2, 2, 2 );

     //click 3
     cameraTween( camera.position, 3, 3, 3 );

});

One solution is to make a generic function by using .one with recursion: 一种解决方案是通过将.one与递归结合使用来创建通用函数:

function LoopEvent(selector, event, calls /*array of functions*/) {
    $(selector).one(event, function() {
        // Execute Function
        calls[0](); 

        // Send current function to the back of the array
        calls.push(calls.shift());

        // Attach next event
        LoopEvent(selector, event, calls);
    });
}

Then you could call it like: 然后可以这样称呼它:

LoopEvent("button", "click", [
  function() { cameraTween( camera.position, 1, 1, 1 ); },  
  function() { cameraTween( camera.position, 2, 2, 2 ); },
  function() { cameraTween( camera.position, 3, 3, 3 ); }
]);

Example Fiddle 小提琴的例子

Create a variable and increment it in the click event 创建一个变量并在click事件中增加它

var i = 1;
$('#myButton').click(function () {
  if (i > 3)
    i = 1;
  cameraTween(camera.position, i, i, i);
  i += 1;
});

使用一些变量来保存点击数,并使用switch来基于此变量调用不同的事件。

var x = 0;

$('button').click(function () {
x = x++;

if (x==1){cameraTween( camera.position, 1, 1, 1 );}
else{
      if (x==2){cameraTween( camera.position, 2, 2, 2 );}
      else{
         cameraTween( camera.position, 3, 3, 3 );
      }
}
});
// Create a variable one level higher than the scope of your click function
var clickCount = 0;

$('button').click(function () {
    clickCount++; // increment the count
    cameraTween(camera.position, clickCount, clickCount, clickCount);
    clickCount %= 3; // Reset every 3
});

Use a variable to track the clicks. 使用变量来跟踪点击。

var clickCount = 1;
$('button').click(function () {
     if(clickCount > 3) {
       clickCount = 1;
     }

     cameraTween( camera.position, clickCount, clickCount, clickCount );
     clickCount++;
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM