简体   繁体   中英

How to use in html body a variable that's been defined in script in the head part

In the following code how can I correctly insert the val testName defined in the function initialize() in the field Name in the body?

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript">

function intialize()
{
    var testName="John";
}
</script>
</head>

<body onload="intialize()">
<input id="Name" type="textbox" value=testName>
</body>
</html>

You can use document ready :

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript">

$(function(){
      $('#Name').val('testName');
});

</script>
</head>

<body>
<input id="Name" type="textbox" value=""/>
</body>
</html>

Used the id, Name, and set the value to 'testName' once the document is ready.

Well, if you're using jQuery, you could just include this in the function:

$("#Name").val(testval);

You might have to put the script in $(document).ready() though.

Try declaring it outside the function

<script type="text/javascript">
var testName;
function intialize()
{
    testName="John";
}
</script>

But it will become a global variable.

This. It's easy, and you don't have to worry about any of this jquery mess.

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript">

function intialize()
{
    var testName="John";
    document.getElementById("Name").value = testname;
}
</script>
</head>

<body onload="intialize()">
<input id="Name" type="textbox">
</body>
</html>

You have jQuery available so USE it. Don't use an older version than 1.6.1 though..

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
var testName="John";
$(document).ready(function() {
    $('#Name').val(testName);
});
</script>
</head>

<body>
<input id="Name" type="text">
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM