如何从“ addEventListener”函数获取元素

时间:2019-10-29 00:00:58

标签: javascript

我刚刚开始处理JS的难部分,可能是我找不到正确的搜索问题,但是如果我展示的话这是可以理解的。

因此,在我的代码中,我想使变量“ str”(全局变量)等于“ addEventListener”函数中的一个元素,该元素应为“ this.responseText”。

var str = "initial";    
xhr.addEventListener("readystatechange", function () {      
    if (this.readyState === this.DONE) {
        str = this.responseText;
    }       
});

if(str != "initial"){
//do something
}

在函数str(等于“ this.responseText”)中显示文本,但是当我想从函数中查看时,它显示未定义。所以我期望str作为函数内部的sn

2 个答案:

答案 0 :(得分:0)

您必须这样做。

var str;    
xhr.addEventListener("readystatechange", function () {      
    if (this.readyState === this.DONE) {
        str = this.responseText; 
        document.getElementById("result").innerHTML = str;
    }       
});

答案 1 :(得分:0)

var str;    

// [1] Since event handling is asynchronous in JS, the event handler
// function 'handleReadyStateChange' will execute and return a result
// at an unpredicted time sometime in the future. 
// Since it is asynchronous, it will not block subsequent code [2] 
// but instead pass the execution step to that line.

xhr.addEventListener("readystatechange", function handleReadyStateChange() {      
    if (this.readyState === this.DONE) {
        str = this.responseText;
    }       
});

// [2] This line will execute immediately after [1] while [1] is STILL 
// at work and has not yet finished its operations.

document.getElementById("result").innerHTML = str;

我认为这样查看您的代码会有所帮助:

var str; // At this point, the value of str is 'undefined'

// This line will ALWAYS execute first, and thus pass the value
// 'undefined' to innerHTML.
// That's why I've placed this line before the xhr code.

document.getElementById("result").innerHTML = str;

// At some point, the callback function will execute and 
// pass the responseText to str subsequently to innerHTML

xhr.addEventListener("readystatechange", function handleReadyStateChange() {      
    if (this.readyState === this.DONE) {
        str = this.responseText;
        document.getElementById("result").innerHTML = str;
    }       
});

最重要的是,在异步操作(例如事件处理,fetch()操作,setTimeout等)中, 您唯一的选择是将取决于异步操作结果的代码放在回调中 函数(对于基于Promise的异步命令,则为then()。

这只是JavaScript出色一章的简介,即异步编程。建议您重新考虑一下代码,然后转到@Bravo指向的文章:How do I return the response from an asynchronous call?

在谈到章节时,有一个很棒的文章详细介绍了异步编程:https://eloquentjavascript.net/11_async.html