html5 javascript,全局变量

html5 javascript, global variables

本文关键字:全局变量 javascript html5      更新时间:2023-09-26

如何创建一个在加载页面时定义的变量,而不是在脚本中?

<script> 
    var comp = 0;
    function mMove(e)
    {        
        var x = e.screenX;           
        if (x > comp + 80)
        {
            comp = x;
            somethingcool();
        }       
    }        
</script>
    <video id="vid_ID" onclick="vidclick()" onmousemove="mMove(event)" controls tabindex="0" autobuffer preload>
        <source type="video/mp4; codecs=&quot;avc1.42E01E, mp4a.40.2&quot;" src="test.mp4"></source>
        <p>Sorry, your browser does not support the &lt;video&gt; element.</p>
    </video>

我有一些视频和onmousemove活动。我希望每次鼠标沿x轴移动80像素时都运行somethingcool()函数。我需要一些方法来存储comp变量。

在您提到要重新加载具有sript的页面之后。问题显而易见您正在覆盖值。以下是可能的解决方案

解决方案

1.请确保将变量声明移出该页。将其移动到主页面。否则,每次加载该页面时,该值都将设置回0。

2.使用LocalStorage存储值。你可以这样做。

<script> 
   if(localStorage.getItem("compValue")){  //First time page load storage will be undefined set the value to 0. On consecutive calls this if block will not execute and hence value will not be overwritten.
     localStorage.setItem("compValue", 0);
   }
    var comp = localStorage.getItem("compValue"); //read from storage
    function mMove(e)
    {        
        var x = e.screenX;           
        if (x > comp + 80)
        {
            comp = x;
            somethingcool();
        }       
    }        
</script>

我更喜欢选项1,因为使用存储器的任务不那么复杂。只需将变量设为全局变量,并注意不要将其改写为

您可以使用document.ready函数。每次加载页面或刷新页面时,它都会与页面一起加载。只需在其中添加comp = 0var comp = 0,就可以将其作为全局JavaScript变量在代码中的任何位置使用。这是一个jquery函数。更多信息,请访问:https://learn.jquery.com/using-jquery-core/document-ready/