首页 > 解决方案 > 将箭头函数与 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>

标签: javascriptarrow-functionshoisting

解决方案


您需要先分配一个值,onChangeHandler 然后再尝试通过传递onChangeHandler给来读取该值addEventListener

作业没有吊起。


推荐阅读