javascript - 将箭头函数与 addEventListener 一起使用会出现错误:未捕获的 TypeError: Cannot read property 'undefined' of undefined at onChangeHandler
问题描述
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Essentials</title>
<style>
* {
text-align: center;
}
/*.car-display {
width: 800px;
height: 500px;
}*/
</style>
</head>
<body>
<select id="mySelect" name="cars">
<option disabled selected='selected'>Select your option</option> <!-- try with aventador as the starting one -->
<option value="Lamborghini Aventador">Lamborghini Aventador</option>
<option value="Ferarri LaFerarri">Ferarri LaFerarri</option>
<option value="McLaren LP">McLaren LP</option>
<option value="Audi R8">Audi R8</option>
</select>
</div>
<div class="test">
<div>djfh</div>
<p>sdjfdf</p>
<h3>djshf</h3>
</div> Also try to dynamically add the pics below here
<div id="picture">
</div>
<script src="myapp4.js"></script>
</body>
</html>
我正在尝试使用箭头功能,但它给了我一个错误。当我这样定义我的函数时它不会出错:function onChangeHandler() {...}为什么会这样?我也试过这个: options.addEventListener('change',onChangeHandler.bind(this); 但它也不起作用。正确的方法是什么?
箭头功能也没有被提升对吗?
var select = document.getElementsByName('cars');
const options = document.getElementById("mySelect");
var picture = document.getElementById("picture");
options.addEventListener('change',onChangeHandler);
onChangeHandler = () => {
var value = this.options[this.selectedIndex].value
console.log(value);
picture.innerHTML = '<img name="image" src="images/' + value + '.jpg">';
var img = document.getElementsByName("image")[0].style.cssText='width: 800px; height: 400px';
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Essentials</title>
<style>
* {
text-align: center;
}
/*.car-display {
width: 800px;
height: 500px;
}*/
</style>
</head>
<body>
<select id="mySelect" name="cars">
<option disabled selected='selected'>Select your option</option> <!-- try with aventador as the starting one -->
<option value="Lamborghini Aventador">Lamborghini Aventador</option>
<option value="Ferarri LaFerarri">Ferarri LaFerarri</option>
<option value="McLaren LP">McLaren LP</option>
<option value="Audi R8">Audi R8</option>
</select>
<div id="picture">
</div>
<script src="myapp4.js"></script>
</body>
</html>
解决方案
您需要先分配一个值,onChangeHandler
然后再尝试通过传递onChangeHandler
给来读取该值addEventListener
。
作业没有吊起。
推荐阅读
- bash - 在 Bash 中的脚本输出中添加标题行(仅当脚本生成输出时)
- python - Tensorflow 2.3.0 - 警告:get_next_as_optional(来自 tensorflow.python.data.ops.iterator_ops)已弃用,将在未来版本中删除
- vba - 在 Solidworks VBA 中创建一条线
- python - 向玩家发牌并使用 player:hand 更新字典
- python-3.x - 有没有办法解压缩嵌套冗余列表的列表?
- python - 检查两个列表中是否有任何共同元素:Python
- c# - 使用 Linq 从同名中选择自定义 ID
- python - Python 出错:TypeError:fit() 缺少 1 个必需的位置参数:'y'
- javascript - updating components when new params are passed to them (VUE JS)
- angular - 有角度的多个流,一个可观察的