node.getElementsByClassName在不同位置的不同行为

时间:2017-07-21 07:13:31

标签: javascript

放置在特定位置的语句console.log(document.getElementsByClassName("buttonQ")[0]);成功执行,但放置在另一个特定位置时的相同语句执行undefined。

这是怎么回事?

两个职位的陈述都通过代码中的评论标记

    //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);
      }

    })();

1 个答案:

答案 0 :(得分:1)

您在文档加载时调用MakeRequest,而另一个语句在文档加载完成之前。因此,在那一刻,DOM上可能还没有元素.buttonQ