我正在尝试使用 js 在提交选择后在 HTML 下拉列表中显示用户选择。我已经搜索了几个小时并尝试了几种不同的方法,但到目前为止没有一个有效。这是我当前的代码:
<script>
var e = document.getElementById("user_engine");
var strUser = e.options[e.selectedIndex].text;
function showEngineChoice() {
document.getElementById('engine').innerHTML =
document.getElementById("strUser").value;
}
</script>
<label><b>What type of engine would you like in your favorite car?</b></label>
<select name="engine_types" id="user_engine">
<option value="1">In-Line V6</option>
<option value="2">3.8L 4-cylinder</option>
<option value="3">Twin Turbo V10</option>
<option value="4">RS-68 Rocket Engine</option>
</select>
<input type="submit" onclick="showEngineChoice()"><br />
<label>You chose: </label><br />
<p><span id="engine"></span></p><br />
<label>Nice Choice!</label>
我尝试了其他一些方法,每次运行代码时,在做出选择后单击提交按钮没有任何反应。我哪里做得不对?
最佳答案
您的脚本位于文档正文之前。这意味着您使用 getElementById
引用的元素未定义。这是一个工作示例:https://codepen.io/pablo-tavarez/pen/NwjrYm?editors=1010
<script>
// await a fully loaded DOM
document.addEventListener('DOMContentLoaded', function () {
// prefetch element references
var ue = document.getElementById("user_engine");
var e = document.getElementById('engine');
// define (global) onsubmit function
window.showEngineChoice = function showEngineChoice() {
// update content with CURRENTLY selected option
e.innerHTML = ue.options[ue.selectedIndex].value;
}
});
</script>
<label>
<b>What type of engine would you like in your favorite car?</b>
</label>
<select name="engine_types" id="user_engine">
<option value="1">In-Line V6</option>
<option value="2">3.8L 4-cylinder</option>
<option value="3">Twin Turbo V10</option>
<option value="4">RS-68 Rocket Engine</option>
</select>
<input type="submit" onclick="showEngineChoice()"><br />
<label>You chose: </label><br />
<p>
<span id="engine"></span>
</p><br />
<label>Nice Choice!</label>
关于javascript - 使用javascript显示html下拉列表选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47245669/