如何动态更改选项显示

How to dynamically change option display

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

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>

您不应该将您的 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>