代码之家  ›  专栏  ›  技术社区  ›  noviceJS

从元素获取.value时未定义

  •  0
  • noviceJS  · 技术社区  · 2 年前

    以下是奖励寿命为1的HTML:

        <h3>PLAYER HEALTH<span value="1" id="bonus-life" >1</span></h3>
        <progress class="playerHealth health" max="100" value="100">100%</progress>
    

    以下是用于获取跨度值和进度元素的JavaScript:

        const playerHealthBar = document.querySelector(".playerHealth");
        const bonusLifeEl = document.querySelector("#bonus-life");
    
        console.log("In index.js bonusLifeEl.innerHTML: " + bonusLifeEl.innerHTML);
        console.log(
          "In index.js - bonusLifeEl value & typeof: " +
            bonusLifeEl.value +
            " " +
            typeof bonusLifeEl.value
        );
        console.log(
          "In index.js - player health value & typeof: " +
            playerHealthBar.value +
            " " +
            typeof playerHealthBar.value
        );
    

    我可以获得正确的playerHealthBar值和类型,但当我尝试使用奖励生命时,我得到的都是未定义的,除非我使用innerHTML,否则我会在innerHTML中获得“值”。

    控制台日志输出:

    In index.js bonusLifeEl.innerHTML: 1
    index.js:8 In index.js - bonusLifeEl value & typeof: undefined undefined
    index.js:14 In index.js - player health value & typeof: 100 number
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   T.J. Crowder    2 年前

    只有 input , select ,以及某些其他特定元素具有 value 属性,而不是 span 元素。即使你放了一个 价值 属性 在您的 跨度 ,不会被 价值 属性(它也是的无效属性 跨度 元素)。要在该元素(而不是其文本内容)上设置任意值,您可以使用 data-* attribute getAttribute dataset 以检索它。

    const value = bonusLifeEl.dataset.value;
    

    // Side note: I'd use `getElementById` rather than `querySelector` here
    const bonusLifeEl = document.querySelector("#bonus-life");
    const value = bonusLifeEl.dataset.value;
    console.log(value,);
    <h3>PLAYER HEALTH<span data-value="1" id="bonus-life" >1</span></h3>