Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

How to refer to a javascript variable in a value field?

I'd like to refer to a variable ("special") in field later in the same script. I've gotten the variable to display with alert boxes and document.write, but don't now how to make to apply its value to the value field in

var special=(10000-health);
var health=(100);

<input style="background:#FF7777;" readonly="readonly" type="text" value="special" id="special" />

this just writes "special" to the box, when I would like the value instead.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You have to set the value explicitly:

document.getElementById('special').value = special;

Note: You can only access the element after it was parsed in the DOM. To be sure, you can insert this part of the script after the element in the HTML. Often JavaScript code is added just before the closing body tag or is only executed when the load event fires. For more information, see Where to place JavaScript in a HTML file.

Update: Here is an example:

<body>
    <input style="background:#FF7777;" readonly="readonly" type="text" value="special" id="special" />

    <script type="text/javascript">
        var health = 100;
        var special = 10000 - health;
        document.getElementById('special').value = special;
    </script>
</body>

References: getElementById, DOM

MDC's JavaScript Guide is also worth reading.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...