所有 假设我有这样的代码
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script type="text/javascript" charset="utf-8">
var figure = document.getElementById("tool");
var selected = figure.options[figure.selectedIndex].value;
if(selected === "pencil"){
alert("Like a pencil");
}
if(selected === 'line'){
alert("Just drag and drop");
}
if(selected === "rect"){
alert("drag and drop for rect");
}
</script>
<p><label>Drawing tool: <select id="tool">
<option value="pencil">Pencil</option>
<option value="rect">Rectangle</option>
<option value="line">Line</option>
</select></label></p>
</body>
</html>
为什么,当我改变droplist的值时,它没有反应?也许我应该添加OnChange?但我没弄明白它是如何运作的...... 谢谢
答案 0 :(得分:1)
您需要将该代码放入事件监听器,例如:
figure.addEventListener('change', function(){
// your code...
});
并将您的脚本放在文档的末尾。
答案 1 :(得分:0)
您需要添加en event handler。当前代码只在页面加载时运行一次。
window.onload(function() {
document.getElementById("tool").addEventListener('change',toolChangeEventHandler);
}
function toolChangeEventHandler() {
if(this.value === "pencil"){
alert("Like a pencil");
} else if(this.value === "line"){
alert("Just drag and drop");
} else if(this.value === "rect"){
alert("drag and drop for rect");
}
}
当您尝试添加事件侦听器时,需要onload事件以确保元素存在。
答案 2 :(得分:0)
您的代码
var figure = document.getElementById("tool");
var selected = figure.options[figure.selectedIndex].value;
if(selected === "pencil"){
alert("Like a pencil");
}
if(selected === 'line'){
alert("Just drag and drop");
}
if(selected === "rect"){
alert("drag and drop for rect");
}
页面加载时执行。要在选择更改时执行此代码,您可以使用上述事件侦听器(方法在所有浏览器中不同)或像这样设置回调(对于单个事件更简单):
<select id="tool" onchange="onSelectChange(this);">...
onSelectChange是这样的函数:
<script type="text/javascript">
var onSelectChange = function(elt) {
var selected = elt.options[elt.selectedIndex].value;
if(selected === "pencil"){
alert("Like a pencil");
}
if(selected === 'line'){
alert("Just drag and drop");
}
if(selected === "rect"){
alert("drag and drop for rect");
}
};
</script>