可以在纯HTML中使用JavaScript变量吗? [英] Can a JavaScript variable be used in plain HTML?

查看:227
本文介绍了可以在纯HTML中使用JavaScript变量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是,在< script> -tags?之外,是否可以在HTML中使用声明和初始化的变量/数组? Fx。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆