即使在" DOMContentLoaded"之后元素选择器返回null

时间:2015-11-25 16:58:31

标签: javascript html domcontentloaded

我在这里遇到一些困难,getElementById返回一个null对象。以下所有代码都放在一个匿名函数中,该函数在" DOMContentLoaded" (事件监听器)。我这样做是为了避免当我尝试设置属性时getElementById无法找到twitter按钮(特别是" data-text")。第一个函数使用getElementById定位元素(页面上的' a'元素)没有问题,但第二个函数返回null。我认为只有在" DOMContentLoaded"之后才能运行它。会解决这个问题吗?我在这里错过了什么? (如果我没有在这里填写足够的代码来展示我尝试做的事情,请告诉我。)

//Add initial invisible quote
(function () {
    var quoteList = document.querySelector(".hidden-quotes").children;
    var randomQuoteNum = Math.round((Math.random() * (quoteList.length - 1)));
    var quoteBox = document.getElementById("quote-box");
    quoteBox.innerHTML = quoteList[randomQuoteNum].innerHTML;
    var tweetQuote = (quoteBox.children[0].innerHTML + " " + quoteBox.children[1].innerHTML);
    var tweetButton = document.getElementById("tweet-button");
    tweetButton.setAttribute("data-text", tweetQuote);
    tweetButton.setAttribute("data-url", " ");
})();

//Set up quote button functionality
var magicButton = document.getElementById("quote-button");
magicButton.addEventListener("click", function () {
    var quoteList = document.querySelector(".hidden-quotes").children;
    var randomQuoteNum = Math.round((Math.random() * (quoteList.length - 1)));
    var quoteBox = document.getElementById("quote-box");
    quoteBox.innerHTML = quoteList[randomQuoteNum].innerHTML;
    var tweetQuote = (quoteBox.children[0].innerHTML + " " + quoteBox.children[1].innerHTML);
    var tweetButton = document.getElementById("tweet-button");
    console.log(tweetButton);
    tweetButton.setAttribute("data-text", tweetQuote);
    quoteBox.style.opacity = 1;
});

这是标记:

<a id="tweet-button" class="twitter-share-button" href="https://twitter.com/intent/tweet">Tweet this.</a>

只有第一个函数似乎能够访问和修改上述元素的属性,而第二个函数甚至找不到它(getDocumentById返回null)。

And here's the codepen.

1 个答案:

答案 0 :(得分:1)

看起来您使用类twitter-share-button设置的按钮会因加载它的脚本而发生一些变化。尝试这样做。

var tweetButton = document.getElementsByClassName("twitter-share-button")[0];