来自事件侦听器的Javascript函数错误
每次更改第一个元素时,我都会收到一个错误,因为我假定要将两个参数传递到“onChangeHandler”中。有没有办法阻止我的代码产生这个错误?一旦我更改了第二个元素,我的代码就可以正常工作,因为我会将两个参数传递到“onChangeHandler”中来自事件侦听器的Javascript函数错误,javascript,Javascript,每次更改第一个元素时,我都会收到一个错误,因为我假定要将两个参数传递到“onChangeHandler”中。有没有办法阻止我的代码产生这个错误?一旦我更改了第二个元素,我的代码就可以正常工作,因为我会将两个参数传递到“onChangeHandler”中 function start(){ var onChangeHandler = function() { calculateAndDisplayRoute(directionsService, directionsDispl
function start(){
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
document.getElementById('pac-input').addEventListener('change',onChangeHandler);
document.getElementById('pac-input2').addEventListener('change', onChangeHandler);
}
根据您的需求为参数设置默认值
onChangeHandler
仅从浏览器接收单个事件。要向其中传递更多内容,请将其嵌套到匿名函数中:
function start(){
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService = '', directionsDisplay = '');
};
document.getElementById('pac-input').addEventListener('change',onChangeHandler);
document.getElementById('pac-input2').addEventListener('change', onChangeHandler);
}
你为什么要嵌套onChangeHandler呢?为什么不直接调用其中的函数呢?它看起来是这样的,会把中间人剪掉:
function start(){
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
document.getElementById('pac-input').addEventListener('change',function(e){
// I do not know what things you want to pass, but it makes no difference for the purposes of this example
onChangeHandler(e, {});
}, false);
document.getElementById('pac-input2').addEventListener('change', function(e){
onChangeHandler(e, {});
});
}
危险的仅限ES6!(目前)更好的解决方案是在函数中设置它们代码>-只是为了兼容性。EDIT:实际上,每次都会以空字符串的形式传递两个参数,因为您传递的是('',)
调用函数时不能使用参数默认值。定义函数时使用它们。您要做的是将(未声明的)变量directionsService
和directionsDisplay
设置为空字符串,然后用这两个空字符串调用calculateAndDisplayRoute
。@torazaburo完全正确(我后来才意识到这是一个函数调用)。这甚至会使任何论点无效,并简单地打断论点的传递!directionsService
和directionsDisplay
应该来自哪里?var directionsService=new google.maps.directionsService;“”“var directionsDisplay=new google.maps.directionsrender;“”方向显示。设置映射(映射);
document.getElementById('pac-input2').addEventListener('change', function(e){
calculateAndDisplayRoute(e, {});
});