Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
767 views
in Technique[技术] by (71.8m points)

arrays - Can a JavaScript variable be used in plain 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>

??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...