繁体   English   中英

如何在HTML中调用外部js文件变量

[英]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";
}

请签入插件http://plnkr.co/edit/HjkwlcnkPwJZ7yyo55q6?p=preview

就像您所做的那样,“文本”变量仅在函数“简单”的范围内设置。

您应该通过在函数外部声明“ text”变量来使其成为全局变量。

var text = "";

function simple()
{
    alert("simple");
    text = "Control";
}

全局声明变量将起作用。

var text = "";
function simple()
{
     text = "Control";
}

朋克

暂无
暂无

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

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