gpt4 book ai didi

javascript - 如何根据从下拉菜单中选择的选项显示 HTML 文本?

转载 作者:行者123 更新时间:2023-11-28 17:55:48 24 4
gpt4 key购买 nike

所以我一直在尝试做的是有一个包含选项的下拉菜单,并根据选择的选项显示一些文本。

我得出的结论是使用 HTML 和 JavaScript 来做到这一点,但我遇到了麻烦。

对于 HTML,我有这个 -

<select id="selectDay">
<option>Choose a Day</option>

对于 JavaScript,我有这个 - `

var select = document.getElementById("selectDay");
var response1 = ("Response if a Day between Monday through Friday is Selected");
var response2 = ("Response if Saturday or Sunday are selected");

var days = ["Sunday", "Monday", "Tuesday", "Wednesday" , "Thursday", "Friday", "Saturday"];

for(var i = 0; i < days.length; i++)
{
var opt = days[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);

}

我主要是通过使用 Google 才走到这一步的,但现在我很困惑。我只是想这样做,这样我就可以说我完成了一个项目。我什至不确定我是否做得正确。

最佳答案

我们需要将 onchange 事件附加到下拉列表,该事件将获取下拉列表值,并根据该值显示 response1response2.下面是示例代码:

var select = document.getElementById("selectDay");
var response1 = ("Response if a Day between Monday through Friday is Selected");
var response2 = ("Response if Saturday or Sunday are selected");

var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

for (var i = 0; i < days.length; i++) {
var opt = days[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}

function getResponse(eleme) {
var e = document.getElementById("selectDay");
var strUser = e.options[e.selectedIndex].value;
if (strUser == 'Saturday' || strUser == 'Sunday') {
console.log(response2)
} else {
console.log(response1);
}
}
<select id="selectDay" onchange=getResponse()>
<option>Choose a Day</option>
</select>

关于javascript - 如何根据从下拉菜单中选择的选项显示 HTML 文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44469964/

24 4 0