简体   繁体   English

如何在html主体中使用在脚本的开头部分定义的变量

[英]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? 在下面的代码中,我如何正确在主体的字段Name中插入在函数initialize()中定义的val testName

<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. 准备好文档后,使用id,Name并将值设置为“ testName”。

Well, if you're using jQuery, you could just include this in the function: 好吧,如果您使用的是jQuery,则可以将其包含在函数中:

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

You might have to put the script in $(document).ready() though. 不过,您可能必须将脚本放入$(document).ready()中。

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. 这很容易,而且您不必担心这种jquery混乱。

<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. 您有可用的jQuery,请使用它。 Don't use an older version than 1.6.1 though.. 不过,请勿使用早于1.6.1的版本。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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