Javascript 如何在html正文中使用已在头部脚本中定义的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6407456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:35:34  来源:igfitidea点击:

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

javascripthtml

提问by Ash

In the following code how can I correctly insert the val testNamedefined in the function initialize()in the field Namein the body?

在下面的代码中,我如何正确地将testName函数initialize()中定义的 val 插入Name到正文的字段中?

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

回答by Marc Uberstein

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

回答by Andreas Eriksson

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() 中。

回答by xyz

Try declaring it outside the function

尝试在函数外声明它

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

But it will become a global variable.

但它会成为一个全局变量。

回答by Isaac Fife

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>

回答by ThiefMaster

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

您有可用的 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>