簡體   English   中英

如何使用用戶輸入javascript創建對象

[英]how to create an object with user input javascript

 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>

我知道如何制作對象,但我不知道如何讓用戶輸入對象的數據並打印到屏幕上。

解決方案:

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列表。 我還向Soldier添加了doReport()方法和常用的doReport()函數,它可以對列表中的所有士兵進行一般報告。 現在,我在每個hire()的末尾調用doReport() ),但你可以通過單擊另一個按鈕來完成。

 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>

我認為我不允許使用推送。 我只是想通過用戶輸入來制作新士兵。我使代碼更好一點。 現在只需要它來實際打印

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM