我有一个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>
请帮帮我。 谢谢。
答案 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)