如何在一次点击(而不是整个点击)内执行一次操作

How to do something once within a click (not the entire click)

本文关键字:一次 执行 操作      更新时间:2023-09-26

如果你有这样的东西:

someVar.click(function() {
  $(this).something.happens.here;
  $(this).something.else.happens.here;
  $(this).something.happens.here.that.should.only.run.once;
});

函数内的第三行是否可以在页面上只运行一次?我能想到的唯一解决方案是编写一个单独的:

someVar.one( "click", function() {
      $(this).something.happens.here.that.should.only.run.once;
    });

但我不想这样做,因为我宁愿将所有内容都保存在一个函数中,主要是因为在第一次单击范围内已经定义了变量。谢谢大家。

如果你在同一个函数中需要它,你可以使用一个标志:

var shouldRun = true;
someVar.click(function() {
  $(this).something.happens.here;
  $(this).something.else.happens.here;
  if (shouldRun) {
    $(this).something.happens.here.that.should.only.run.once;
    shouldRun = false;
  }
});

正如您提到的,将事件附加到one是最优雅的解决方案。或者,您可以设置一个全局变量来指示函数是否已运行:

var functionHasRun = false
someVar.click(function() {
    $(this).something.happens.here;
    $(this).something.else.happens.here;
    !functionHasRun && $(this).something.happens.here.that.should.only.run.once;
    functionHasRun = true;
});

如果你不喜欢全局变量,你可以在引发事件的元素上设置一个data属性:

someVar.click(function() {
    $(this).something.happens.here;
    $(this).something.else.happens.here;
    !someVar.data('functionHasRun') && $(this).something.happens.here.that.should.only.run.once;
    someVar.data('functionHasRun', true);
});
var track=true;
someVar.click(function() {
  $(this).something.happens.here;
  $(this).something.else.happens.here;
  if(track)$(this).something.happens.here.that.should.only.run.once;
  track=false;
});
.one将是

我使用的,否则我只会使用一个可以在执行后重新定义为空的函数。

var onlyrunonce = function(){
    $(this).something.happens.here.that.should.only.run.once;
    onlyrunonce = $.noop;
}
someVar.click(function(e) {
  $(this).something.happens.here;
  $(this).something.else.happens.here;
  return onlyRunOnce.call(this,e);
});

这应该为您完成:

var handled = false;
someVar.click(function() {
  $(this).something.happens.here;
  $(this).something.else.happens.here;
  if(!handled){
      $(this).something.happens.here.that.should.only.run.once;
      handled = true;
  }
});