放置在特定位置的语句console.log(document.getElementsByClassName("buttonQ")[0]);
成功执行,但是放置在另一个特定位置的同一语句执行不确定。
这里发生了什么 ??
两个位置的语句均通过代码中的注释标记
//quotes
(function(){
window.addEventListener("load", makeRequest);
function makeRequest(){
//-----the below statement "console.log" executes succesfully----
console.log(document.getElementsByClassName("buttonQ")[0]);
document.getElementsByClassName("buttonQ")[0].addEventListener("click", makeRequest);
function reqListener() {
if(httpR.readyState === XMLHttpRequest.DONE) {
var quote;
if(httpR.status === 200) {
quote = JSON.parse(httpR.responseText);
document.getElementsByClassName("quote")[0].innerHTML = quote[0].body;
} else {
alert("There was a problem with the request!")
}
}
}
var httpR;
httpR = new XMLHttpRequest();
httpR.onreadystatechange = reqListener
httpR.open("GET", "https://quote-api.glitch.me/pull/1", true);
httpR.send();
}
//----------------------tweet-------------------
//------the below statement "console.log" gives the result "undefined"----
console.log(document.getElementsByClassName("buttonQ")[0]);
//document.getElementsByClassName("buttonT")[0].addEventListener("click", tweetEvent);
function tweetEvent() {
document.getElementsByClassName("quote")[0].normalize();
var tweetToShare = document.getElementsByClassName("quote")[0].childNodes[0].nodeValue;
var urlForTweetButton = document.getElementsByClassName("twitter-share-button")[0].getAttribute("href");
urlForTweetButton = urlForTweetButton + "?hashtags=quotes&text=" + encodeURIComponent(tweetToShare);
}
})();
最佳答案
您在文档加载时调用MakeRequest
,而另一条语句在文档加载完成之前。因此,在那时,DOM上可能还没有元素.buttonQ
。
关于javascript - node.getElementsByClassName在不同位置的不同行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45231326/