使用 JavaScript 显示名字和姓氏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31346822/
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
Display first and lastname with JavaScript
提问by John.P
I'm learning JavaScript and I'm trying to make it so the user is able to enter a name and lastname and then click a send button. When that happens the name and lastname is displayed on the the screen just bellow.
我正在学习 JavaScript,我正在努力使用户能够输入姓名和姓氏,然后单击发送按钮。发生这种情况时,姓名和姓氏将显示在下方的屏幕上。
The problem is that it doesn't work. Nothing happens when the user clicks the send button.
问题是它不起作用。当用户单击发送按钮时什么也没有发生。
Here is how I tired it.
这就是我如何厌倦它。
HTML:
HTML:
<body>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
<br>
<input type="button" value="Send" onclick="MyFunction()">
<div id="here"></div>
<body>
JavaScript:
JavaScript:
function MyFunction() {
var first, second;
first = document.getElementById("firstname").value;
second = document.getElementById("lastname").value;
document.GetElementById("here").InnerHTML = first;
document.GetElementById("here").InnerHTML = second;
}
回答by Zakaria Acharki
This is your example worked fine after some changes :
这是您的示例经过一些更改后工作正常:
HTML:
HTML:
<input type="text" name="firstname" id="firstname">
<input type="text" name="lastname" id="lastname">
JS:
JS:
myFunction = function() {
var first = document.getElementById("firstname").value;
var second = document.getElementById("lastname").value;
document.getElementById("here").innerHTML = first+" "+second;
}
Find your example here : jsFiddle.
在这里找到你的例子:jsFiddle。
回答by Robert Lee
You wanted this as your output code:
您希望将其作为输出代码:
document.getElementById("here").innerHTML = first + " " + second;
The G and I should be lower case and you should output both first and last names at the same time using string concatenation. Note though, that this will have XSS vulnerabilities.
G 和 I 应该是小写的,您应该使用字符串连接同时输出名字和姓氏。但请注意,这将存在 XSS 漏洞。
Also, change your input name attributes to id attributes.
此外,将您的输入名称属性更改为 id 属性。
回答by taxicala
You are using getElementByIdbut you dont have any element with the given Ids, I believe you've forgot to add id's to your input elements:
您正在使用getElementById但您没有任何具有给定 Id 的元素,我相信您已经忘记将 id 添加到您的输入元素中:
<input type="text" name="firstname" id="firstname">
<input type="text" name="lastname" id="lastname">
You might also want to change GetElementByIdfor getElementByIdas js is case sensitive.
您可能还想更改GetElementByIdforgetElementById因为 js 区分大小写。

