在最后一行,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';
})
})