如何将变量从外部 JavaScript 传递到 HTML 表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19644906/
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
How to pass Variable from External JavaScript to HTML Form
提问by user2929293
I have been trying to pass a value from an external javascript file to an HTML form with no luck. The files are rather large so I am not sure I can explain it all but ill try.
我一直在尝试将值从外部 javascript 文件传递到 HTML 表单,但没有成功。这些文件相当大,所以我不确定我能不能解释清楚,但我会尝试。
Basically a user clicks a link then a js file is initiated. Immediately after a new HTML page loads.
基本上,用户单击一个链接,然后启动一个 js 文件。在新的 HTML 页面加载后立即。
I need this value passed to the HTML page in a form field.
我需要将此值传递到表单字段中的 HTML 页面。
Javascript:
Javascript:
var divElement = function(){
divCode = document.getElementById(div1).innerHTML;
return divCode; };
document.getElementById('adcode').value = divElement();
Afterwards it should be passed to this Form field
之后它应该被传递到这个表单字段
HTML Form Field:
HTML 表单字段:
<p>Ad Code:<br>
<input type="text" name="adcode" id="adcode"/>
<br>
</p>
Thanks for any help!
谢谢你的帮助!
回答by Douglas Barbin
Your HTML file needs to reference the JavaScript js
file. Have a function in your JavaScript that returns the value that you need. Use JavaScript (I like jQuery) to set the form field to what you need.
您的 HTML 文件需要引用 JavaScriptjs
文件。在您的 JavaScript 中有一个返回您需要的值的函数。使用 JavaScript(我喜欢 jQuery)将表单字段设置为您需要的内容。
JS file:
JS文件:
<script>
var divElement = function(){
divCode = document.getElementById(div1).innerHTML;
return divCode; };
document.getElementById('adcode').value = divElement();
function GetDivElement() {
return divElement();
}
</script>
HTML file:
HTML文件:
<p>Ad Code:
<br />
<input type="text" name="adcode" id="adcode"/>
<br />
</p>
<script src="wherever that js file is" />
<script>
window.onload = function() {
document.getElementById('adcode').value = GetDivElement();
}
</script>
Although, really, this might do what you want (depending on what you are trying to do):
虽然,真的,这可能会做你想做的(取决于你想要做什么):
<p>Ad Code:
<br />
<input type="text" name="adcode" id="adcode"/>
<br />
</p>
<script src="wherever that js file is" />
<script>
window.onload = function() {
GetDivElement();
}
</script>
回答by Meowsome
Can it be this?:
可以是这个吗:
function divElement(divCode){
return divCode;
}
divElement(document.getElementById('adcode').value);