是否可以使用函数将 document.getElementByID().innerHTML 推送到 HTML 文件?

Is it possible to use a function to push the document.getElementByID().innerHTML to an HTML file?

我带着社区的另一个问题回来了。我知道有很多关于 document.getElementByID() 主题的问题和答案,但我找不到任何指向我正在寻找的路径的东西,它可能根本不存在。

在我的基于文本的 javascript 游戏中,我有很多跨度,我希望缩短代码的长度,对于在对象内声明和更改变量的每个实例,将其推送到HTML 页面,我不得不使用 document.getElementByID().

发送垃圾邮件

例如,在我的 HTML 文件中我有:

<div id="attributes">
                <div id="main_attributes">
                    <p>
                        Name: <span id="Player.Name">0</span>&emsp;&emsp; Gender: <span id="Player.Gender">0</span><br />
                        Class: <span id="Player.ClassType">0</span><br /><br />
                        Health: <span id="Player.Health">0</span><br />
                        Mana: <span id="Player.Mana">0</span><br />
                        Strength: <span id="Player.Strength">0</span><br/>
                        Defense: <span id="Player.Defense">0</span><br />
                        Endurance: <span id="Player.Endurance">0</span><br />
                        Intelligence: <span id="Player.Intelligence">0</span><br />
                        Current Location: <span id="currentarea">0</span>
                    </p>
                </div>
            </div>

我用它从 Hero 原型制作了一个对象 "Player":

function Hero(Gender, Sexiness, Name, classType, Health, Mana, Strength, Defense, Endurance, Intelligence, Friend, Gold, BattleHealth, BattleMana, BattleStamina,  Experience, Level, Karma,) {
    this.Gender = Gender;
    this.Sexiness = Sexiness;
    this.Name = Name;
    this.ClassType = classType;
    this.Health = Health;
    this.Mana = Mana;
    this.Strength = Strength;
    this.Defense = Defense;
    this.Endurance = Endurance;
    this.Intelligence = Intelligence;
    this.Friend = Friend;
    this.Gold = Gold;
    this.BattleHealth = BattleHealth;
    this.BattleMana = BattleMana;
    this.BattleStamina = BattleStamina;
    this.Experience = Experience;
    this.Level = Level;
    this.Karma = Karma;
}
let Player = new Hero("Spirit", 0, "Spirit", "Undetermined One", 0, 0, 0, 0, 0, 0, "None", 10, 0, 0, 0, 0, 1, 0);

定义了一些常量:

const Male = {
    Type: "Male",
    Health: 100,
    Mana: 20,
    Strength: 20,
    Defense: 5,
    Endurance: 15,
    Intelligence: 5,
    Sexiness: 1,
    Friend: "Duncan",
}
const Female = {
    Type: "Female",
    Health: 80,
    Mana: 60,
    Strength: 16,
    Defense: 4,
    Endurance: 12,
    Intelligence: 10,
    Sexiness: 2,
    Friend: "Morgana",
}

还有一个性别分配函数:

function genderAssign() {
    switch (Player.Gender) {
        case "Male":
            Player.Gender = Male.Type;
            Player.Health = Male.Health;
            Player.Mana = Male.Mana;
            Player.Strength = Male.Strength;
            Player.Defense = Male.Defense;
            Player.Endurance = Male.Endurance;
            Player.Intelligence = Male.Intelligence;
            Player.Sexiness = Male.Sexiness;
            Player.Friend = Male.Friend;
            Armor.UpperClothesName = "Chest";
            Armor.LowerClothesName = "Fig Leaves";
            Armor.HelmetName = "Head";
            Armor.BodyName = "Body";
            Armor.ArmName = "Arms";
            Armor.WaistName = "None";
            Armor.LegName = "Legs";
            Armor.BootsName = "Feet";
            Weapons.RightHand = "Right Hand";
            Weapons.LeftHand = "Left Hand";
            Armor.LegCoveringsName = "Hair";
            break;
        case "Female":
            Player.Gender = Female.Type;
            Player.Health = Female.Health;
            Player.Mana = Female.Mana;
            Player.Strength = Female.Strength;
            Player.Defense = Female.Defense;
            Player.Endurance = Female.Endurance;
            Player.Intelligence = Female.Intelligence;
            Player.Sexiness = Female.Sexiness;
            Armor.UpperClothesName = "Nip Coverings";
            Armor.LowerClothesName = "Fig Leaves";
            Armor.HelmetName = "Head";
            Armor.BodyName = "Body";
            Armor.ArmName = "Arms";
            Armor.WaistName = "None";
            Armor.LegName = "Legs";
            Armor.BootsName = "Feet";
            Weapons.RightHand = "Right Hand";
            Weapons.LeftHand = "Left Hand";
            Armor.LegCoveringsName = "Smooth Legs";
            Player.Friend = Female.Friend;
            break;
        default:
    }
    return;
}

我不想做如下事情:

            Player.Gender = Male.Type;
            document.getElementByID("Male.Type").innerHTML = Male.Type
            Player.Health = Male.Health;
            document.getElementByID("Male.Health").innerHTML = Male.Health
            Player.Mana = Male.Mana;
            document.getElementByID("Male.Mana").innerHTML = Male.Mana

等等... 有没有办法做类似的事情:

function printPlayer() {

    Player.Gender = $('#Player.Gender');
    Player.Sexiness = $('#Player.Sexiness');
    Player.Health = $('#Player.Health');
    Player.Mana = $('#Player.Mana');
    Player.Strength = $('#Player.Strength');
    Player.Defense = $('#Player.Defense');
    Player.Endurance = $('#Player.Endurance');
    Player.Intelligence = $('#Player.Intelligence');
    Player.Friend = $('#Player.Friend');
    Player.Gold = $('#Player.Gold');
    Player.Experience = $('#Player.Experience');
    Player.Level = $('#Player.Level');
    Player.ClassType = $('#Player.ClassType');
}

function printPlayer() {

    document.getElementById("Player.Sexiness").innerHTML = Player.Sexiness;
    document.getElementById("Player.Health").innerHTML = Player.Health;
    document.getElementById("Player.Mana").innerHTML = Player.Mana;
    document.getElementById("Player.Strength").innerHTML = Player.Strength;
    document.getElementById("Player.Defense").innerHTML = Player.Defense;
    document.getElementById("Player.Endurance").innerHTML = Player.Endurance;
    document.getElementById("Player.Intelligence").innerHTML = Player.Intelligence;
    document.getElementById("Player.Friend").innerHTML = Player.Friend;
    document.getElementById("Player.Gold").innerHTML = Player.Gold;
    document.getElementById("Player.Experience").innerHTML = Player.Experience;
    document.getElementById("Player.Level").innerHTML = Player.Level;
    document.getElementById("Player.ClassType").innerHTML = Player.ClassType;
}

然后从内部调用它,比如 genderAssign() 函数?

抱歉,如果这有点冗长,但我宁愿让你更广泛地了解我正在做的事情,而不是让你去猜测。以上功能我都试过了,好像都不行。错误是:

TypeError: document.getElementById(...) is nullUpdatePlayerCharacter.js:22:14

printPlayer file:///C:/Users/Melseph/Desktop/Game Design/PhoenixDestitute/scripts/UpdatePlayerCharacter.js:22

genderAssign file:///C:/Users/Melseph/Desktop/Game Design/PhoenixDestitute/scripts/CharacterStats.js:78

<anonymous> file:///C:/Users/Melseph/Desktop/Game Design/PhoenixDestitute/scripts/PhoenixDestitute.js:45
jQuery 2

我假设是因为我在 printPlayer() 函数中没有值,但我被困在那里,找不到方向。难道按照我尝试的方式做是不可能的吗?

--编辑--

我似乎总是忽略这部分,这就是为什么我认为每个人都倾向于指向一个按钮,这是我的错误,抱歉...

我有一个供用户回答问题的表格和一个 window 显示玩家所做的更新,我已经添加了 document.getElementByID()...当然)当我把它们拿出来的时候把它杀了。我可以通过 console.log(Player) 看到 Player 对象中的所有项目都在更新,但是我找不到更简单的方法将内部 HTML 推送到 HTML 文件。

这是我的控制台 ID 代码和屏幕截图:

<div class="console">
<div id="console_wrapper">
    <div id="console">
        <p>Would you like to begin your adventure? Type <u><b>yes</b></u> or <u><b>no</b></u>.</p>
        <!--
        PLACEHOLDER: THIS IS WHERE YOUR CHOICES ARE INPUT
        -->
        <div id="placeholder"></div>
    </div>
</div>
<form id="form" onsubmit="return false;">
    <input type="text" autocomplete="off" id="command_line" placeholder="User Input Here" autofocus="autofocus" />
</form>

$(document).ready(function() {
$("#console").fadeIn(3000); //Console fades in.
$(document).keypress(function(key) { //When a key is press:
    if (key.which === 13 && $('#command_line').is(':focus')) { //If enter key is pressed and the focus is on the command line:
        var input = $('#command_line').val().toLowerCase(); //Express what is in the command line in lower case.
        $('#command_line').val(""); //Erase the value of what is shown in the command box.
        $("#console").animate({ scrollTop: "999999999px" }, 'slow'); //Scroll the console to the bottom.
     }
}

不确定这是否会改变我的问题的答案,或者使用按钮是否是唯一的方法。

此代码段应为您提供一些处理 Player 对象属性的想法,包括在页面上显示它们。
(有关脚本特定功能的解释,请参阅代码内注释。)

//Identifies button for demo
const myButton = document.getElementById("my-button");

// Calls `printInfoToPage` method when button is clicked
myButton.addEventListener("click", printInfoToPage);

// Defines Player object
const Player = {
  Sexiness: 5,
  Health: 5,
  Mana: 3,
  Strength: 4,
  Defense: 3,
  BowlingScore: 5
};

// (Arrow function) prepends "Player." to its string argument 
const mapPropNameToElementId = (propName) => "Player." + propName;

// Takes two strings, updates textContent of matching element if possible
function setElementTextById(id, text){
  element = document.getElementById(id);
  if(element){ // Makes sure element exists before proceeding
    element.textContent = text; // `.innerHTML` would also work
  }
};

function printInfoToPage(){

  // Static `.keys` method on `Object` gets an object's property names
  const playerPropNames = Object.keys(Player);

  // `for...of` loops through array
  for(let prop of playerPropNames){

    // Gets IDs
    const elementId = mapPropNameToElementId(prop);
    
    // Gets value
    const storedValue = Player[prop];

    // Updates element on page
    setElementTextById(elementId, storedValue);
  }
}
<span>Sexiness: </span><span id="Player.Sexiness"></span> <br/>
<span>Health: </span><span id="Player.Health"></span> <br/>
<span>Mana: </span><span id="Player.Mana"></span> <br/>
<span>Strength: </span><span id="Player.Strength"></span> <br/>
<span>Defense: </span><span id="Player.Defense"></span> <br/>
<br/>
<button id="my-button">Show Player Info</button>

编辑
顺便说一句,代码可以(更短 and/or)更可重用。为了清晰起见,我经常使用更冗长的代码,但重复编写相同的命令式代码不仅冗长而且更容易出错且更难维护。

如果您想处理各种属性组(即各种对象,例如盔甲和武器),可以修改 printInfoToPage 函数以将对象及其标识字符串作为参数,例如:

const
  category1 = { prop1: 111, prop2: 222 },
  category2 = { prop3: 333, prop4: 444 },
  printInfoToPage = (prefix, group) => {
    for(let prop in group){// `for...in` is for objects
      setElementValueById(prefix + prop, group[prop]);
    }
  },
  setElementValueById = (id, val) => {
    const el = document.getElementById(id);
    // `input` elements have a `value` property
    if(el?.tagName == "INPUT"){ el.value = val; }
  };

printInfoToPage("category1.", category1);
printInfoToPage("category2.", category2);
<label> prop1: <input id="category1.prop1" /></label><br />
<label> prop2: <input id="category1.prop2" /></label><br />
<br />
<label> prop3: <input id="category2.prop3" /></label><br />
<label> prop4: <input id="category2.prop4" /></label>