开发者

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 Na开发者_如何学编程me 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.


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>


Try declaring it outside the function

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

But it will become a global variable.


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜