繁体   English   中英

js的新手。 我如何要求用户输入功能

[英]newbie to js. how do i ask user for input with function

改进的hello完成以下程序,以便向用户询问其名字和姓氏,然后显示sayHello()函数的结果。

// Say hello to the user
function sayHello(firstName, lastName) {
  const message = `Hello, ${firstName} ${lastName}!`;
  return message;
}

// TODO: ask user for first and last name
// TODO: call sayHello() and show its result
function askForName() {
  var person = prompt("Please enter your first and last name:");
  if (person !== null) {
    var firstName = person.split(' ')[0]; 
    var lastName = person.split(' ')[1];
    console.log(sayHello(firstName, lastName));
  }
}

function sayHello(firstName, lastName) {
  const message = `Hello, ${firstName} ${lastName}!`;
  return message;
}

askForName();

结果将记录到控制台。

尽管我已经从答案中省略了模板文字(出于兼容性原因) 这应该向您展示一些基本的JavaScript。

 //<![CDATA[ /* external.js */ var doc, bod, htm, M, I, S, Q, old = onload; // for use on other loads onload = function(){ if(old)old(); // change old var name if using technique on other pages doc = document; bod = doc.body; htm = doc.documentElement; M = function(tag){ return doc.createElement(tag); } I = function(id){ return doc.getElementById(id); } S = function(selector, within){ var w = within || doc; return w.querySelector(selector); } Q = function(selector, within){ var w = within || doc; return w.querySelectorAll(selector); } I('f').onsubmit = function(){ return false; } var first = I('first'), last = I('last'), show = I('show'), out = I('out'); show.onclick = function(){ out.innerHTML = first.value+' '+last.value; first.value = last.value = ''; } } //]]> 
 /* external.css */ html,body{ padding:0; margin:0; } body{ background:#000; overflow-y:scroll; } .main{ width:940px; background:#ccc; padding:20px; margin:0 auto; } 
 <!DOCTYPE html> <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'> <head> <meta http-equiv='content-type' content='text/html;charset=utf-8' /> <meta name='viewport' content='width=device-width' /> <title>Test Template</title> <link type='text/css' rel='stylesheet' href='external.css' /> <script type='text/javascript' src='external.js'></script> </head> <body> <div class='main'> <form id='f' name='f'> <input id='first' name='first' type='text' placeholder='First Name' /> <input id='last' name='last' type='text' class='empty' placeholder='Last Name' /> <input id='show' name='show' type='button' value='Display Input' /> </form> <div id='out'></div> </div> </body> </html> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM