简体   繁体   English

将值从JavaScript传递到另一个js文件

[英]Passing a value from a javascript to another js file

My code is... 我的代码是...

<script type="text/javascript">
   function changeval() {
     $total = parseInt($("#small").val()) + parseInt($("#medium").val());
   }
</script>

How can I pass '$total' to another js file, say main.js. 我如何将'$ total'传递给另一个js文件,例如main.js。

Call changeval function from another file, save/use returned value. 从另一个文件调用changeval函数,保存/使用返回值。

function changeval() {
    return parseInt($("#small").val()) + parseInt($("#medium").val());
}

Or have one global variable save value inside the same variable and access it from another file. 或者,将一个全局变量保存在同一变量内的值,然后从另一个文件访问它。

Make sure that $total is assigned to the global scope and make sure the script where you want to use it is below the script where you assign it. 确保将$ total分配给全局范围,并确保要使用它的脚本在分配它的脚本下方。 Be careful about polluting the global scope too much because it can make code that is very tricky to debug and can cause strange errors if you overwrite a native global variable. 注意不要过度污染全局范围,因为它会使代码调试起来非常棘手,而且如果您覆盖本地全局变量,可能会导致奇怪的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM