Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
来自事件侦听器的Javascript函数错误_Javascript - Fatal编程技术网

来自事件侦听器的Javascript函数错误

来自事件侦听器的Javascript函数错误,javascript,Javascript,每次更改第一个元素时,我都会收到一个错误,因为我假定要将两个参数传递到“onChangeHandler”中。有没有办法阻止我的代码产生这个错误?一旦我更改了第二个元素,我的代码就可以正常工作,因为我会将两个参数传递到“onChangeHandler”中 function start(){ var onChangeHandler = function() { calculateAndDisplayRoute(directionsService, directionsDispl

每次更改第一个元素时,我都会收到一个错误,因为我假定要将两个参数传递到“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',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, {});
   });