Javascript 如何在一次单击(而不是整个单击)内执行一次操作
如果你有这样的东西:Javascript 如何在一次单击(而不是整个单击)内执行一次操作,javascript,jquery,Javascript,Jquery,如果你有这样的东西: 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()
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;
});
如果您不喜欢globals,可以在引发事件的元素上设置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);
});
.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;
}
});
在我看来,.one解决方案是最好的,否则每次单击都会有额外的代码运行,从而防止第三次单击。如果不想单独调用
.one()
,则可能需要一些标志来测试发生的事情。在这里。应该。仅。针对。
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;
}
});