如何使用用户输入javascript创建对象

时间:2017-10-17 23:15:15

标签: javascript html object



window.onload = Soldier;

function Soldier(allegiance,armor,weapon){
    this.allegiance = allegiance;
    this.armor = armor;
    this.weapon = weapon;
}
document.getElementById("soldier").innerHTML = 

var soldier1 =  new Soldier("Theosis", true, "Sword");
alert(soldier1.allegiance);

<DOCTYPE HTML>

<html>
<head>
    <script src = "objscript.js"> </script>
</head>
<body>
  Allegiance: <input type ="text" id = "allegiance"><br/><br/>
  Armor:  <input type ="text" id = "armor"><br/><br/>
  Weapon(s): <input type ="text" id = "weapon"><br/><br/>
  <input type = "button" id="button" value = "Submit"><br/>
  <p id = "soldier"> </p>
</body>
</html>
&#13;
&#13;
&#13;

我知道如何制作物品,但我不知道如何让用户输入物体的数据并在屏幕上打印。

2 个答案:

答案 0 :(得分:0)

解决方案:

<强> HTML

Allegiance: <input type ="text" id = "allegiance"><br/><br/>
Armor:  <input type ="text" id = "armor"><br/><br/>
Weapon(s): <input type ="text" id = "weapon"><br/><br/>
<input type = "button" id="button" onclick="hire()" value = "Submit"><br/>
<p id="output"></p>

<强> JS

var soldiers = [];

function Soldier(allegiance, armor, weapon){
  this.allegiance = allegiance;
  this.armor = armor;
  this.weapon = weapon;
  this.doReport = function () {
    return this.armor + ' and ' + this.weapon;
  }
}

function doReport() {
   output = "";
   for(var i = 0; i < soldiers.length; i++) {
      output += (i + 1) + ") " + soldiers[i].doReport() + "; ";
   }
   document.getElementById("output").innerHTML = output;
}

function hire() {
  var soldier =  new Soldier(
    document.getElementById("allegiance").value, 
    document.getElementById("armor").value, 
    document.getElementById("weapon").value
  );
  soldiers.push(soldier);
  doReport();
}

我添加了函数hire()并使用提交按钮绑定它。新的soldier对象正被推送到soldiers列表中。我还将doReport()方法添加到了Soldier和常见的doReport()函数中,该函数对列表中的所有士兵进行了总体报告。现在,我在每个doReport()的末尾拨打hire(),但您可以点击另一个按钮来执行此操作。

答案 1 :(得分:0)

window.onload = submit;
function Soldier(allegiance,armor,weapon){
this.allegiance = "allegiance";
this.armor = armor;
this.weapon = weapon;


var soldier1 =  document.getElementById("atext").value;

document.getElementById("soldier").innerHTML = " allegiance: " + soldier.allegiance + " <br/> " + " armor: " + soldier.armor + "</br>" + "Weapon(s): "+ soldier.weapon;
}

function submit(){
	var submitButton = document.getElementById("button");
	submitButton.onclick = Soldier;
}
<DOCTYPE HTML>

<html>
<head>
<script src = "objscript.js"> </script>
</head>

<body>
Allegiance: <input type ="text" id = "atext"><br/><br/>
Armor:  <input type ="text" id = "armor"><br/><br/>
Weapon(s): <input type ="text" id = "weapon"><br/><br/>
<input type = "button" id="button" value = "Submit"><br/>
<p id = "soldier"> </p>

</body>
</html>

我不认为我允许使用推送。我只是想让用户输入新士兵。我使代码更好一些。现在只需要它实际打印