1

在最后一行,getElementsByClassName找不到元素,因为该loadhtml函数是一个 AJAX 调用。

如何使用异步函数或 ES6 生成器或承诺,以使getElementsByClassName最后一行工作?

    TotalArticleNumber = 3;

    for (let i = TotalArticleNumber; i > 0; i--) {
      loadhtml('./article/test' + i + '.md', function(e) {
        sdf(i, e);
      });
    };


    function loadhtml(url,callback) {
     var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
       if (xhttp.readyState == 4) {
        if( xhttp.status == 200){
         var response = xhttp.responseText;
         (callback)(response);
        }
       };
     };

      xhttp.open("GET", url, true);
      xhttp.send();
    };



    function sdf(i, e) {
      var node = document.createElement("DIV");
      var node1 = document.createElement("A");
      var node2 = document.createElement("H1");
      var node3 = document.createElement("P");

      node.setAttribute('class', 'articleInner');
      node1.setAttribute('class', 'openArticle');
      node2.setAttribute('class', 'title');
      node2.setAttribute('id', i);
      node2.innerHTML = e.match(re);
      node3.innerHTML = converter.makeHtml(e.replace(re1, ""));
      node1.appendChild(node2);
      node1.appendChild(node3);
      node.appendChild(node1);

      document.getElementById('articleContent').appendChild(node);
    }

    Array.prototype.forEach.call(document.getElementsByClassName('title'), function(item) {
      item.addEventListener('click', function() {
        document.getElementById('realArticle').style.display = 'block';
        document.body.style.background = 'gray';
      })
    })
4

1 回答 1

0

如果你想使用这个async特性,你需要将它的核心包装在一个async function块中,并await为你使用的每个 Promise 使用关键字:

假设loadHtml是一个异步函数,你可以使用这个:

function loadHTML(url) {
    return new Promise((resolve, reject) => {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4) {
                var response = xhttp.responseText;
                if (xhttp.status == 200) {
                    resolve(response);
                } else {
                    reject(response)
                }
            };
        };
        xhttp.open("GET", url, true);
        xhttp.send();
    })
};
async function loadHtmlAndMakeElements(){
    TotalArticleNumber = 3;
    let promises = []
    for (let i = TotalArticleNumber; i > 0; i--) {
        promises.push(new Promise((resolve, reject) => {
            loadHTML(`./article/test${i}.md`).then(e => {
                sdf(i, e);
                resolve()
            });
        }))
    }
    await Promise.all(promises);
    Array.prototype.forEach.call(document.getElementsByClassName('title'), function(item) {
        item.addEventListener('click', function() {
            document.getElementById('realArticle').style.display = 'block';
            document.body.style.background = 'gray';
        })
    })
}
function sdf(i, e) {
    var node = document.createElement("DIV");
    var node1 = document.createElement("A");
    var node2 = document.createElement("H1");
    var node3 = document.createElement("P");
    node.setAttribute('class', 'articleInner');
    node1.setAttribute('class', 'openArticle');
    node2.setAttribute('class', 'title');
    node2.setAttribute('id', i);
    node2.innerHTML = e.match(re);
    node3.innerHTML = converter.makeHtml(e.replace(re1, ""));
    node1.appendChild(node2);
    node1.appendChild(node3);
    node.appendChild(node1);
    document.getElementById('articleContent').appendChild(node);
}
loadHtmlAndMakeElements()
于 2016-07-14T03:53:38.060 回答