如何在一次点击(而不是整个点击)内执行一次操作
How to do something once within a click (not the entire click)
如果你有这样的东西:
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;
}
});
相关文章:
- If语句只执行一次
- JavaScript 只在 php 代码中执行一次
- 如果只有一次有条件,如何执行
- 是节点.js一次只执行一个上下文
- 就绪函数上的指令只能执行一次
- 如何在if循环中只执行一次
- Javascript执行一次
- Jquery on('单击')..函数只执行一次
- 如何在一次有条件的ng单击时执行多个调用
- 如何只执行一次ajaxStart和ajaxEnd
- 使用Greasemonkey每5秒执行一次Javascript
- 只执行一次jquery animate
- jQuery如果大于则执行操作,但只执行一次
- 制作一个$window.location.reload(true);在离子/角度中仅执行一次
- 正则表达式回调函数只执行一次
- 如何循环函数数组并在单击时一次执行一个
- 代码只执行一次,但应该继续执行
- Casper.start 的循环只执行一次
- 如何在一次点击(而不是整个点击)内执行一次操作
- 在一次执行中多次运行Jasmine Spec