繁体   English   中英

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

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

在下面的代码中,我如何正确在主体的字段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>

您可以使用准备好的文档:

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

准备好文档后,使用id,Name并将值设置为“ testName”。

好吧,如果您使用的是jQuery,则可以将其包含在函数中:

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

不过,您可能必须将脚本放入$(document).ready()中。

尝试在函数外声明它

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

但是它将成为一个全局变量。

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

您有可用的jQuery,请使用它。 不过,请勿使用早于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