【问题标题】:How to dynamically change option display如何动态更改选项显示
【发布时间】:2021-11-03 16:41:19
【问题描述】:

我希望用户提交他们的姓名,这些姓名将在选项显示中。

HTML

<form action="#">
        <input type="text" id="p1Name">
        <input type="text" id="p2Name">
        <button id="start">Start</button>
</form>
<label for="selected">Select Player</label>
<select name="" id="selected">
            <option value="p1"><span id="select1">Player 1</span></option>// So "Player 1" and "Player 2" should be replaced by users's names 
            <option value="p2"><span id="select2">Player 2</span></option>
</select>

Javascript

const p1 = {
    displaySelect: document.querySelector('#select1')
}
const p2 = {
    displaySelect: document.querySelector('#select1')
}


const startButton = document.querySelector('#start');
startButton.addEventListener('click', () => {
    let nameOne = document.getElementById('p1Name').value;
    let nameTwo = document.getElementById('p2Name').value;
    p1.displaySelect.textContent = nameOne;
    p2.displaySelect.textContent = nameTwo;
})

似乎 p1.displaySelect 为空。我试图在互联网上查找它,但我真的找不到。请看我的代码。

app.js:26 Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')
    at HTMLButtonElement.<anonymous>

【问题讨论】:

    标签: javascript html forms dom select


    【解决方案1】:

    您不应该将您的 id 放在 option 标记中。相反,它应该在 option 标记本身内。

    下面代码中的 preventDefault 方法有助于阻止 HTML 重定向您。

    希望这会有所帮助?

    const p1 = {
        displaySelect: document.querySelector('#select1')
    }
    const p2 = {
        displaySelect: document.querySelector('#select2')
    }
    
    
    const startButton = document.querySelector('#start');
    startButton.addEventListener('click', (e) => {
        e.preventDefault()
        let nameOne = document.getElementById('p1Name').value;
        let nameTwo = document.getElementById('p2Name').value;
        p1.displaySelect.textContent = nameOne;
        p2.displaySelect.textContent = nameTwo;
    })
    <form action="#">
      <input type="text" id="p1Name">
      <input type="text" id="p2Name">
      <button id="start">Start</button>
    </form>
    <label for="selected">Select Player</label>
    <select name="" id="selected">
      <option value="p1" id="select1"><span>Player 1</span></option>// So "Player 1" and "Player 2" should be replaced by users's names
      <option value="p2" id="select2"><span>Player 2</span></option>
    </select>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      • 2020-02-06
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 2014-01-21
      相关资源
      最近更新 更多