jQuery移动按钮单击处理程序触发两次?

Ale*_*ski 3 jquery jquery-mobile

这是代码......简单(现在全局定义的变量).我第一次点击它按预期工作...第二次howvere导致事件连续两次发射,这是我现在想要的......任何想法???

$(document).on("vclick", "#timer", function() {

  console.log(past_ts);
  if(past_ts === 0) {
    past_ts = new Date().getTime();
    $(this).text("Stop Set Timer");
  }
  else {
    curr_ts = new Date().getTime();
    diff_ts = ((curr_ts - past_ts) / 1000);

    past_ts = 0; // Reset timer

    $(this).text("Start Set Timer");

  }
});
Run Code Online (Sandbox Code Playgroud)

Ray*_*ram 6

简单.我有两种方法可以解决这个问题.

1)e.stopImmediatePropagation()打开功能后使用(第二行).一定要传递event参数.

$(document).on("vclick", "#timer", function(e) {
                                      //    ^ note this param
  e.stopImmediatePropagation();

  console.log(past_ts);
  if(past_ts === 0) {
    past_ts = new Date().getTime();
    $(this).text("Stop Set Timer");
  }
  else {
    curr_ts = new Date().getTime();
    diff_ts = ((curr_ts - past_ts) / 1000);

    past_ts = 0; // Reset timer

    $(this).text("Start Set Timer");

  }
});
Run Code Online (Sandbox Code Playgroud)

文档可以在这里找到: http ://api.jquery.com/event.stopimmediatepropagation/

要么

2)尝试使用off().on()技术.这可以确保如果您已经绑定了行为,它将取消绑定,然后重新绑定.

$(document).off("vclick", "#timer").on("vclick", "#timer", function() {

  console.log(past_ts);
  if(past_ts === 0) {
    past_ts = new Date().getTime();
    $(this).text("Stop Set Timer");
  }
  else {
    curr_ts = new Date().getTime();
    diff_ts = ((curr_ts - past_ts) / 1000);

    past_ts = 0; // Reset timer

    $(this).text("Start Set Timer");

  }
});
Run Code Online (Sandbox Code Playgroud)