2

我在 getElementById 返回一个空对象时遇到了一些困难。以下所有代码都放在了一个匿名函数中,该函数在“DOMContentLoaded”(事件监听器)时被调用。我这样做是为了避免当我尝试设置属性(特别是“数据文本”)时 getElementById 无法找到 twitter 按钮。第一个函数使用 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)。

这是codepen。

4

1 回答 1

1

看起来你用类设置的按钮twitter-share-button被加载它的脚本稍微改变了。试着像这样得到它。

var tweetButton = document.getElementsByClassName("twitter-share-button")[0];
于 2015-11-25T17:12:16.780 回答