我可以在return语句中使用警报框吗?

时间:2018-11-08 09:10:24

标签: javascript

这是我的代码:

function myFunction() {
  var name = document.getElementById('myname').value;
  var phone = document.getElementById('myphone').value;
  var country = document.getElementById('mycountry').value;
  var mail = document.getElementById('mymail').value;
  return alert(name + " , " + phone + " , " + country + " , " + mail);
}
<div>
  Name<input type="text" id="myname"><br> Phone
  <input type="text" id="myphone"><br> Country <input type="text" id="mycontry"><br> Mail
  <input type="text" id="mymail"><br>

  <button onclick="myFunction()">Try it</button>
</div>

如果是,为什么我没有得到预期的结果?谁能看到我的代码并纠正我?

3 个答案:

答案 0 :(得分:0)

如果要使用,可以将return与alert()函数一起使用。但是,您无法从alert()获取任何字段的值。如果要从myFunction()获取字段值。您必须创建对象。 例如

//create constructor

function myFunction(myname, myphone, mycountry, mymail) {
    this.name = myname;
    this.phone = myphone;
    this.country = mycountry;
    this.mail = mymail;
}

//create object

var obj = new myFunction("testName", "testPhone", "testCountry", "testMail");

window.onload = alert(obj.name + " , " + obj.phone + " , " + obj.country + " , " + obj.mail);

关于JavaScript - object's functions referencing its fields

答案 1 :(得分:0)

这是您的工作代码。您选择了错误的ID:

<input type="text" id="mycontry" />更改为 id="mycountry"

function myFunction() {
  var name = document.getElementById('myname').value;
  var phone = document.getElementById('myphone').value;
  var country = document.getElementById('mycountry').value;
  var mail = document.getElementById('mymail').value;
  
  //var phone = document.getElementById('myphone').value;
  //var country = document.getElementById('mycountry').value;
  //var mail = document.getElementById('mymail').value;
  return alert(name + " , " + phone + " , " + country + " , " + mail);
}
<div>
  Name <input type="text" id="myname" ><br>
  Phone <input type="text" id="myphone" ><br> 
  Country <input type="text" id="mycountry"><br> 
  Mail <input type="text" id="mymail" value=""><br>

  <button onclick="myFunction()">Try it</button>
</div>

答案 2 :(得分:0)

您无需返回任何内容,因为您没有在任何地方使用返回值。您可以发出警报:

function myFunction() {
  var name = document.getElementById('myname').value;
  var phone = document.getElementById('myphone').value;
  var country = document.getElementById('mycountry').value;
  var mail = document.getElementById('mymail').value;
  alert(name + " , " + phone + " , " + country + " , " + mail);
}
<div>
  Name
  <input type="text" id="myname"><br> 
  Phone
  <input type="text" id="myphone"><br> 
  Country 
  <input type="text" id="mycountry"><br> 
  Mail
  <input type="text" id="mymail"><br>

  <button onclick="myFunction()">Try it</button>
</div>

请注意,您的实际问题出在国家(地区)字段上:(您当前的代码抛出错误,因为选择的ID错误,所以无法读取属性值null)

  <input type="text" id="mycountry">
  <!-- was missing u in here ^^ -->