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

时间:2015-07-03 08:20:29

标签: javascript jquery html

我有一个js文件。

文件名: propoties.js

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

这些是我的HTML代码。我想要的是警告html中的 text 变量。

<html>
<script type='text/javascript' src='path/propoties.js'></script>    
<script>
    simple();
    alert(text); /* It is not working */
</script>
 </html>

请帮帮我。 谢谢。

4 个答案:

答案 0 :(得分:3)

您的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演示。

答案 1 :(得分:1)

如果要提醒外部文件中的文本,则需要将变量声明为全局,如下所示。

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

或者您可以使用window关键字

声明变量
function simple()
{
    alert("simple");   
    window.text = "Control";
}

请检查plunker http://plnkr.co/edit/HjkwlcnkPwJZ7yyo55q6?p=preview

答案 2 :(得分:1)

就像你做的那样,“text”变量只在“简单”函数的范围内设置。

你应该通过在函数之外声明它来使“text”变量成为全局变量。

var text = "";

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

答案 3 :(得分:0)

全局声明变量将起作用。 即

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

请参阅plunker