可以在纯 HTML 中使用 JavaScript 变量吗? [英] Can a JavaScript variable be used in plain HTML?
本文介绍了可以在纯 HTML 中使用 JavaScript 变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的意思是,声明和初始化的变量/数组能否在 HTML 中使用,在 标签之外?外汇.
What I mean is, can a variable/array declared and initialized be used in HTML, outside the <script>
-tags? Fx.
<script type="text/javascript">
var foo = array('placeholder1', 'placeholder2');
</script>
<body>
<p><!--access the variable here-->foo[0]</p>
</body>
在这种情况下如何访问变量/数组?像这样:
How do you access the variable/array in this case? like this:
<p><script type="text/javascript">document.print(foo[0])</script></p>
??
推荐答案
有两种方法可以做到这一点.这是更好的:
Two ways to do this. This is the better one:
<script type="text/javascript">
// make sure to do this onLoad, for example jQuery's $()
var foo = array('placeholder1', 'placeholder2');
document.getElementById("fooHolder").innerHTML = foo.toString();
</script>
...
<p id="fooHolder"></p>
或者你可以这样做(正如 Marcel 指出的那样,它在 XHTML 中不起作用,而且无论如何都不应该使用):
Or you could do it this way (which, as Marcel points out, doesn't work in XHTML and really shouldn't be used anyway):
<p><script type="text/javascript">document.write(foo)</script></p>
这篇关于可以在纯 HTML 中使用 JavaScript 变量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文