我创建了一个下拉列表。像这样,下拉菜单在该下拉菜单中将1
作为默认值显示,但是我也想显示在我首先选择任何内容之前分配给该显示值的值。这意味着,在单击任何内容之前,我希望它默认显示“ 您选择的:一个”。我如何做到最好?
function myFunction() {
var x = document.getElementById("mySelect").value;
if (x == "one") {
document.getElementById("demo").innerHTML = "You selected: " + x;
} else if (x == "two") {
document.getElementById("demo").innerHTML = "You selected: " + x;
} else if (x == "three") {
document.getElementById("demo").innerHTML = "You selected: " + x;
}
}
<select name="test" id="mySelect" onchange="myFunction()">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<p id="demo"></p>
谢谢!
答案 0 :(得分:2)
只需在加载时调用myFunction()
function myFunction() {
var x = document.getElementById("mySelect").value;
if (x == "one") {
document.getElementById("demo").innerHTML = "You selected: " + x;
} else if (x == "two") {
document.getElementById("demo").innerHTML = "You selected: " + x;
} else if (x == "three") {
document.getElementById("demo").innerHTML = "You selected: " + x;
}
}
myFunction(); // call onload
<select name="test" id="mySelect" onchange="myFunction()">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<p id="demo"></p>
已更新,删除if
语句
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
myFunction(); // call onload
<select name="test" id="mySelect" onchange="myFunction()">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<p id="demo"></p>
答案 1 :(得分:1)
添加事件处理程序作为html元素的属性(即内联事件处理程序)不是一个好主意。 Why not?
相反,在单独的脚本中,在开始时添加选定的值,并向change
添加document
处理程序,以在做出选择后显示选定选项的值。
{
// at start: fill p#demo
document.querySelector(`#demo>span`).textContent =
document.querySelector(`#mySelect`).value;
// change handler
document.addEventListener(`change`, evt => evt.target.id === `mySelect` &&
(document.querySelector(`#demo>span`).textContent = evt.target.value));
}
<select name="test" id="mySelect">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<p id="demo">Current selection: <span></span></p>
答案 2 :(得分:1)
您可以在页面加载时调用函数。
像下面一样,(function(){})();
是一个自调用函数,可在页面加载时触发。
function myFunction() {
var x = document.getElementById("mySelect").value;
if(x == "one"){
document.getElementById("demo").innerHTML = "You selected: " + x;}
else if(x == "two"){
document.getElementById("demo").innerHTML = "You selected: " + x;}
else if(x == "three"){
document.getElementById("demo").innerHTML = "You selected: " + x;
}
}
(function(){
myFunction()
})();
<select name="test" id="mySelect" onchange="myFunction()">
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<p id="demo"></p>