[英]How to call external js file variable in HTML
I have a js file. 我有一个js文件。
File Name: propoties.js 文件名: propoties.js
function simple()
{
alert("simple");
var text = "Control";
}
These is my html code. 这些是我的html代码。 What i want is alert that text variable in html.
我想要的是提醒HTML中的文本变量。
<html>
<script type='text/javascript' src='path/propoties.js'></script>
<script>
simple();
alert(text); /* It is not working */
</script>
</html>
Please help me these. 请帮我这些。 Thank you.
谢谢。
Your js file: 您的js文件:
var simple=function(){
var textMultiple = {
text1:"text1",
text2:"text2"
};
return textMultiple;
}
In your html: 在您的html中:
<html>
<script type='text/javascript' src='./relative/path/to/propoties.js'></script>
<script>
alert(simple().text1);
alert(simple().text2);
</script>
</html>
If you want to alert the text in external file you need to declare the variable as global like below. 如果要警告外部文件中的文本,则需要将变量声明为global,如下所示。
var text = "Control";
function simple()
{
text="Changed";
alert("simple");
}
or you can declare the variable using window keyword 或者您可以使用window关键字声明变量
function simple()
{
alert("simple");
window.text = "Control";
}
please check in plunker http://plnkr.co/edit/HjkwlcnkPwJZ7yyo55q6?p=preview 请签入插件http://plnkr.co/edit/HjkwlcnkPwJZ7yyo55q6?p=preview
like you did it the "text" variable is only set in the scope of the function "simple" . 就像您所做的那样,“文本”变量仅在函数“简单”的范围内设置。
you should make the "text" variable global by declaring it outside the function. 您应该通过在函数外部声明“ text”变量来使其成为全局变量。
var text = "";
function simple()
{
alert("simple");
text = "Control";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.