javascript 获取提示框的值到另一个函数中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14579592/
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
Getting the value of prompt box into another function
提问by DjangoDev
Please check out the code below. I want to get the value entered in the prompt box into function dis(). How can I do that?
请查看下面的代码。我想把提示框中输入的值放到函数dis()中。我怎样才能做到这一点?
<!DOCTYPE html>
<html>
<head>
<script>
function display()
{
var z=prompt("enter your name...");
if(z!=null)
{
document.getElementById("demo").innerHTML="thankyou"+z+"..";
document.getElementById("case").style.display='block';
}
else
document.getElementById("demo").innerHTML="thankyou";
}
function dis()
{
var a=document.getElementById("aaa").value;
alert("your mark is"+a);
}
</script>
</head>
<body>
<p id="demo">click on the button.....</p>
<button type="button" onclick="display()">submit</button>
<div id="case" style="display:none">
<input type="text" id="aaa" name="myText" onDblClick="dis()">enter your mark
</div>
</body>
</html>
回答by Prashant16
If you want to directly pass value to dis() function then change your script to
如果您想直接将值传递给 dis() 函数,则将脚本更改为
function display() {
var z = prompt("enter your name...");
if (z != null) {
document.getElementById("demo").innerHTML = "thankyou " + z + "..";
document.getElementById("case").style.display = 'block';
dis(z);
}
else
document.getElementById("demo").innerHTML = "thankyou";
}
function dis(arg) {
alert("your mark is" + arg);
}
回答by nnnnnn
If you want the value to be accessible from independent functions you'll need to store it in a global variable:
如果您希望可以从独立函数访问该值,则需要将其存储在全局变量中:
<script>
var userName = null;
function display() {
userName = prompt("enter your name...");
if (userName != null) {
document.getElementById("demo").innerHTML="thankyou "+userName +"..";
document.getElementById("case").style.display='block';
} else
document.getElementById("demo").innerHTML="thankyou";
}
function dis() {
var a=document.getElementById("aaa").value;
alert(userName + ", your mark is"+a);
}
</script>
Note that if the functions are completely independent they'll all need to test whether the variable has a value yet. In your case the dis()
function is only called from a control that is made visible after a value has been set, but note that the user might click the button again and then cancel - in which case the name will be set back to null
but the case
element will still be visible.
请注意,如果函数是完全独立的,它们都需要测试变量是否有值。在您的情况下,该dis()
函数仅从设置值后可见的控件中调用,但请注意,用户可能会再次单击该按钮然后取消 - 在这种情况下,名称将被设置回,null
但case
元素将仍然可见。