Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.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_Events - Fatal编程技术网

如何在Javascript事件侦听器中返回对象?

如何在Javascript事件侦听器中返回对象?,javascript,events,Javascript,Events,我做了一个javascript事件监听器,但我不确定我是否违反了任何规定。这就是我的代码的外观: const url = window.location; document.getElementById('save-employee-allowance').addEventListener('click', (e) =>{ let allowance = document.getElementById('allowance').addEventListener('change',

我做了一个javascript事件监听器,但我不确定我是否违反了任何规定。这就是我的代码的外观:

const url = window.location;
document.getElementById('save-employee-allowance').addEventListener('click', (e) =>{
    let allowance = document.getElementById('allowance').addEventListener('change', (e) =>{
        let item  = document.getElementById('allowance').value;
        if(item){
            let httpRequest = new XMLHttpRequest();
            httpRequest.open('GET', url.origin+"/api/allowance/search/1/"+item);
            httpRequest.send();
            httpRequest.onreadystatechange = function(){
                if(this.readyState == 4 && this.status == 200){
                    if(typeof(JSON.parse(httpRequest.responseText).id) !== 'undefined'){
                        return JSON.parse(httpRequest.responseText);
                    }
                }
            }
        }
    });
    console.log('Allowance Val >>> '+allowance);
});
在运行时,它为我的余量变量提供了一个未定义的值。
我应该怎么做才能返回并获取我的更改侦听器的值?

你不能这样做。我明白了。所以我必须将它分开。好的,将解码后的JSON从XHR回调中传递给某个函数。为什么要在另一个函数中添加侦听器呢?
addEventListener
不仅不能返回事件处理程序的返回值,而且不能返回,因为:1。当
addEventListener
返回时,事件处理程序尚未调用,2。事件处理程序将在每次事件发生时调用,而不仅仅是一次。有关详细信息,请参阅和链接问题的答案。