只执行一次函数 [英] execute function only once

查看:90
本文介绍了只执行一次函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个greasemonkey脚本,并且只想在页面加载后调用 start 函数 - 这是针对facebook的。首先我开始使用以下代码:

I'm writing a greasemonkey script and want to call the start function only once after the page loads - it's for facebook. First I started with following code:

function start(){
    alert("hello");
}

start();

start()函数执行了一次以上。所以我将代码更改为以下内容:

The start() function was executed more then once. So I changed the code to following:

jQuery.noConflict();
window.stoop = 0;
jQuery(document).ready(function(){
    if(window.stoop == 0){
        start();
    }
    window.stoop = 55;
    //or window.stoop++;
});


function start(){
    alert("hello");
}

问题是window.stoop值不会改变。

The problem is that the window.stoop value won't change.

我试过

var stoop = 0;
stoop++;

var obj = {};
obj.stoop = 0;
obj.stoop++;

,但这些方式都不起作用。

too, but these ways didn't work neither.

我做错了什么?我现在在欧洲 - 当晚,所以我稍后会回答你的问题。

What am I doing wrong? I'm in Europe right now -it's night, so I will answer your questions later.

推荐答案

问题在于你的整体Greasemonkey脚本不止一次执行。 Greasemonkey将在iframe上运行,就像它们是主页一样 - 如果iframe与 @include 匹配, @exclude @match 你的脚本指令。

The issue is that your whole Greasemonkey script is executing more than once. Greasemonkey will run on iframes, just as though they were the main page -- if the iframe matches the @include, @exclude, and @match directives of your script.

尝试跟踪状态是没有意义的,每个脚本执行一次,该函数只运行一次,除非你故意多次调用它(问题中没有显示)。并且脚本通常不能在执行实例之间共享信息(这里也不需要)。

There is no point in trying to track state like that, the function will only run once per script execution, unless you deliberately call it more than once (Which is not shown in the question). And scripts can't normally share information between execution instances (nor is that needed here).

此外,不需要使用 jQuery(文件).ready()因为,除非你将脚本注入目标页面,否则Greasemonkey默认在 document.ready 时触发。

Also, there is no need to use jQuery(document).ready() because, unless you are injecting the script into the target page, Greasemonkey fires at document.ready by default.

解决多次运行问题:


  1. 调整 @include @exclude @match 指令消除尽可能多的不受欢迎的iframe你可以合理地。

  2. 在脚本顶部附近添加如下代码:

  1. Tune your @include, @exclude, and @match directives to eliminate as many undesired iframes as you reasonably can.
  2. Add code like this near the top of your script:

if (window.top != window.self)  //-- Don't run on frames or iframes.
    return;


这篇关于只执行一次函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆