[英]How to call external js file variable in HTML
我有一个js文件。
文件名: propoties.js
function simple()
{
alert("simple");
var text = "Control";
}
这些是我的html代码。 我想要的是提醒HTML中的文本变量。
<html>
<script type='text/javascript' src='path/propoties.js'></script>
<script>
simple();
alert(text); /* It is not working */
</script>
</html>
请帮我这些。 谢谢。
您的js文件:
var simple=function(){
var textMultiple = {
text1:"text1",
text2:"text2"
};
return textMultiple;
}
在您的html中:
<html>
<script type='text/javascript' src='./relative/path/to/propoties.js'></script>
<script>
alert(simple().text1);
alert(simple().text2);
</script>
</html>
这是一个plunkr演示。
如果要警告外部文件中的文本,则需要将变量声明为global,如下所示。
var text = "Control";
function simple()
{
text="Changed";
alert("simple");
}
或者您可以使用window关键字声明变量
function simple()
{
alert("simple");
window.text = "Control";
}
就像您所做的那样,“文本”变量仅在函数“简单”的范围内设置。
您应该通过在函数外部声明“ text”变量来使其成为全局变量。
var text = "";
function simple()
{
alert("simple");
text = "Control";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.