[英]Display the name entered?
I'm learning JavaScript/HTML, and I need help to adjust the JS script function so that when the user clicks "submit" it will display the name that the user enters.我正在学习 JavaScript/HTML,我需要帮助调整 JS 脚本功能,以便当用户单击“提交”时,它会显示用户输入的名称。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Names</title>
<link type="text/css" rel="stylesheet" href="css/style.css"/>
<script type="text/javascript" rel="script" src="js/scripts.js" defer></script>
</head>
<body>
<label for="name">Your Name:</label>
<input id="name" name="name" type="text"/>
<input id="submit-button" name="submit-button" type="submit" value="Submit"/>
<h3>Result</h3>
<div id="output">
Form not submitted yet.
</div>
<script>
function DisplayName(){
document.getElementById('submit-btn').innerHTML =
document.getElementById("name").value;
}
console.log("Your name is: " + name);
</script>
</body>
</html>
We can make a couple adjustments and get this working just fine.我们可以进行一些调整并使其正常工作。 The common method would be to add a click event listener to your button that once clicked will trigger a function.常见的方法是向您的按钮添加一个单击事件侦听器,单击该侦听器后将触发一个函数。
Let's add this to your button: onclick="displayName()
, note I am writing the function in camelCase. This is a good practice for js functions. Here's how your button looks now:让我们将它添加到您的按钮中: onclick="displayName()
,注意我正在使用驼峰命名法编写函数。这是 js 函数的一个很好的做法。这是您的按钮现在的外观:
<input id="submit-button" name="submit-button" type="submit" value="Submit" onclick="displayName()"/>
Next let's do the javascript.接下来让我们来做 javascript。 We can keep it all in one simple function, the displayName()
function.我们可以将其全部保存在一个简单的函数中,即displayName()
函数。
function displayName(){
var name= document.getElementById("name").value;
console.log('Your name is: ' + name);
}
First, this gets the value of the "name" id, then this will log it to the console.首先,它获取“名称”ID 的值,然后将其记录到控制台。
If you want to enhance this slightly, you can also make a few adjustments to the js to display the name in the output id
tag you created.如果您想稍微增强一下,您还可以对 js 进行一些调整,以在您创建的输出id
标签中显示名称。 Here's how your final work might look.这是您的最终作品的外观。
function showName(){ var name= document.getElementById("name").value; document.getElementById("output").innerText = name; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Names</title> <link type="text/css" rel="stylesheet" href="css/style.css" /> <script type="text/javascript" rel="script" src="js/scripts.js" defer></script> </head> <body> <label for="name">Your name: </label> <input type="text" id="name" name="name"> <input id="submit-button" name="submit-button" type="submit" value="Submit" onclick="showName()" /> <h3>Result</h3> <div id="output"> Form not submitted yet. </div> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.