javascript 在警报中使用 getElementById

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29723690/
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-10-28 10:58:25  来源:igfitidea点击:

Use getElementById in Alert

javascript

提问by JugglingBob

This is my code:

这是我的代码:

<form method="GET">
<input type="text" class="form" name="name" placeholder="Enter your name!" id="name">
<input type="submit" onclick="return clicked();" value="I'm ready!">
</form>
<script>
function clicked() {
 return confirm('Hiya,');
}
var email = document.getElementById('name').value;
</script>

I've had a search around, but I cannot find any single topicwhich matches my question. On the return confirmation where it currently just says Hiya, I would like it to then also include the name which the user entered into the text input.

我四处搜索,但找不到与我的问题相匹配的任何主题。在当前只说 Hiya 的返回确认中,我希望它还包含用户在文本输入中输入的名称。

Help would be appreciated.

帮助将不胜感激。

采纳答案by Alex

This should do what you want:

这应该做你想做的:

<form method="GET">
  <input type="text" class="form" name="name" placeholder="Enter your name!" id="name">
  <input type="submit" onclick="return clicked();" value="I'm ready!">
</form>
<script>
  function clicked() {
    var name = document.getElementById('name').value;


    return confirm('Hiya,' + name);
  }

  var email = document.getElementById('name').value;
</script>

回答by Christos

You could try something like this:

你可以尝试这样的事情:

function clicked() {
    // Here we select the html element with id name and
    // we read it's value.
    var name = document.getElementById('name').value;

    // Then my simply concatenating the Hiya with the above value, name
    // we show to the confirm value the message we want.
    return confirm('Hiya,'+name);
}

function clicked() {
    var name = document.getElementById('name').value;
    return confirm('Hiya, '+name);
}
<form method="GET">
<input type="text" class="form" name="name" placeholder="Enter your name!" id="name">
<input type="submit" onclick="return clicked();" value="I'm ready!">
</form>

回答by RobG

You can pass the value in the call:

您可以在调用中传递值:

<input name="name" ...>
<input type="button" onclick="return clicked(this.form.inputName.value);">

where inputNameis the name of the input, and in the function:

其中inputName是输入的名称,在函数中:

function clicked(value) {
 return confirm('Hiya, ' + value);
}

However, since you named the input name, it attempts to get the form's name, not the name control so rename the control to, say, userName, then:

但是,由于您命名了输入name,它尝试获取表单的名称,而不是名称控件,因此将控件重命名为userName,然后:

<input name="userName" ...>
<input type="button" onclick="return clicked(this.form.userName.value);">