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