且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Ajax加载新内容时如何停止JavaScript执行?

更新时间:2023-12-04 23:46:52

即使第一个<script>块已被替换,但由于javascript的工作原理,您仍会看到控制台日志.

Even though the 1st <script> block has been replaced, you see the console logs because of the way javascript works.

您的匿名功能

function(){
    console.log("I am page 1");
}

将继续存在并继续执行,直到您致电clearInterval或离开此页面为止.

will live on and keep executing till you call clearInterval or move away from this page.

添加点击处理程序(例如$('#some_button').on("click",function(evt){/*do something*/});

This is also the case when you add a click handlers eg $('#some_button').on("click",function(evt){/*do something*/});

即使您已声明变量,例如<script>var x='data1';</script> 然后删除封闭的<script>标记,变量x将继续存在.

Even if you have a variable declared, like <script>var x='data1';</script> and then you delete the enclosing <script> tag, the variable x will continue to exist.

在两种情况下,对函数和变量的引用都存储在某个位置.事件处理程序保留对setInterval和click处理程序函数的引用. 对您声明的任何varfunction的引用都保存在window对象(除非您使用关闭)

In both cases, the references to the functions and variables are stored somewhere. References to the setInterval, and click handler function are held by the event handlers. A reference to any var and function you declare is held in the window object (unless you use a closure).

在新加载的脚本中,您可以重新分配内容:函数的行为将是最后一次加载的行为.对该函数的任何调用都将执行新指令,因为它们现在也已经分配给了窗口对象(作用域).

In your newly loaded script, you could re-assign stuff: the behavior of a function will be the last loaded behavior. Any calls made to that function will execute the new instructions because they too have now been assigned to the window object(scope).

总而言之,

  1. 您需要清除间隔
  2. 您声明的函数和变量将一直存在,直到您对其进行更改


Re:评论中的问题


Re:Question in comment

哦,所以,如果我声明一个函数的新行为,它不会像静态编程语言那样给我一个错误.如果我可以保持命名不变,那将为我节省很多工作.我想我要做的就是clearInterval,并保持所有功能不变.

oh, so If I declare a new behavior for a function, it wouldn't give me an error like it would with static programming languages. It 2ould save me a lot of work if I can keep the namings the same. I guess all I need to do is clearInterval, and keep whatever functions as they are.

对,而不是与其他编程语言形成平行,请尝试将它们视为将脚本标记注入DOM时立即解释的指令.因此,实际上您只是在重新分配window对象的属性.为了更好地理解这一点,请在chrome上打开开发者控制台并按顺序运行它们:

Right but rather than draw a parallel to other programming languages, try and see these as instructions that are interpreted immediately when you inject the script tag into the DOM. So, what you are doing is actually just re-assigning the properties of the window object. To understand this better, open the developer console on chrome and run these in order:

window.hasOwnProperty("xy")
var xy=1
window.hasOwnProperty("xy")
window.xy
xy="foo"
typeof window.xy 
typeof window 

这应该有助于您了解JavaScript引擎如何处理您的代码.

This should help you understand how the JavaScript engine is treating your code.