简体   繁体   English

将变量值传递给脚本函数中的变量(Javascript)

[英]Passing a variable value to a variable in a script function (Javascript)

I would like to know how to pass the value of a variable in JavaScript file to a variable in a script function which is written on top of the HTML file. 我想知道如何将JavaScript文件中的变量值传递给脚本函数中的变量,该函数写在HTML文件之上。

I wrote it like this: 我这样写的:

myjsfile.js : myjsfile.js

var abc = "10";

HTML file : HTML文件

<html>
<head>
<script type="text/javascript">
(function() {

var test = document.createElement('script'); test.type = 'text/javascript'; test.async = true;

test.src = 'testquery.js';

var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(test, s);

alert(abc);
})();

</script>
</head>
<body>
</body>
</html>

I am not getting the output. 我没有得到输出。 Please help! 请帮忙! Thanks in advance. 提前致谢。

Basically I am trying to create a jquery plugin just like Google analytics. 基本上我正在尝试像Google分析一样创建一个jquery插件。

该脚本必须先加载,尝试使用onload

test.onload=function(){alert(abc);}
<html>
  <head>
    <script type="text/javascript" src="testquery.js"></script>
    <script type="text/javascript">
        alert(abc);
    </script>
 </head>
 <body></body>
</html>

try this: 尝试这个:

(function() {

    var test = document.createElement('script');
    document.getElementsByTagName('head')[0].appendChild(test);
    test.type = 'text/javascript';
    test.src = 'testquery.js';

    test.onload = function () {
        alert(abc);
    }

})();​

well.. the onload has already been told but you should at least switch your way of appending it to the head. 好吧.. onload已经被告知了,但你应该至少改变你的方式将其附加到头部。

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

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