我已经阅读了许多有关此主题,但没有任何效果。我正在尝试做一些非常简单的事情,但似乎无法使其正常工作。我试图让下拉框的元素更改段落文本中的值。这是我正在运行的脚本:
fmap
这是我的div的选择选项:
Functor
我的浏览器控制台没有任何错误。我觉得我确实很想念它,但是我无法弄清楚。感谢您的帮助!
编辑1:我根据以下答案更新了脚本。当前有1个fmap
正在更新:高级标记...。正在尝试查找差异。
编辑2:其工作。我搞砸了if / else if语句。
答案 0 :(得分:2)
您需要侦听下拉菜单的change事件,否则您的代码在页面加载后将只运行一次。
<script>
window.onload = function fn(){
var x = document.getElementById("DescChange");
var y = document.getElementById("CostChange");
var a = document.getElementById("dropdown"); // <-- removed ".value"
a.addEventListener('change', function() { // <-- added event handler
if (a.value == 0){
x.innerHTML = "Description: Basic care for car including wax and buffer";
y.innerHTML = "Total cost:" + 59.99;
}
else{
x.innerHTML = "";
y.innerHTML = "";
}
});
}
</script>
包装代码的匿名函数称为event handler。每当下拉列表的值更改时,就会调用它。
答案 1 :(得分:2)
对我来说 snwflk 代码很好
我只认为使用更简单的代码,
具有更好的变量名
并在不需要时不使用innerHTML =>使用 textContent
window.onload = function() {
let
DescChange = document.getElementById("Desc-Change"),
CostChange = document.getElementById("Cost-Change"),
mySelect = document.getElementById("dropdown")
;
mySelect.onchange = function(){
switch (mySelect.value) {
case '0':
DescChange.textContent = "Description: Basic care for car including wax and buffer";
CostChange.textContent = "Total cost: " + 59.99;
break;
case '1':
DescChange.textContent = "Mid-level care for car including Basic services and repainting"
CostChange.textContent = "Total cost: " + 119.99;
break;
case '2':
DescChange.textContent = "Advanced care for car including Basic, Intermediate and interior + window repair";
CostChange.textContent = "Total cost: " + 299.99;
break;
default:
DescChange.textContent = "";
CostChange.textContent = "";
}
}
}
<div>
<h2><u>Products and Services</u></h2>
<h4>
<select id="dropdown">
<option value="empty" disabled selected> please select </option>
<option value="0">Basic</option>
<option value="1">Intermediate</option>
<option value="2">Advanced</option>
</select>
<p id="Desc-Change">1</p>
<p id="Cost-Change">2</p>
<p></p>
<p></p>
</h4>
</div>