【问题标题】:Element selector returning null even after "DOMContentLoaded"?即使在“DOMContentLoaded”之后元素选择器也返回 null?
【发布时间】:2015-11-26 01:12:16
【问题描述】:

我在 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)。

And here's the codepen.

【问题讨论】:

  • 请让我们看看实际按钮的标记是什么样子的 :)
  • 同时显示 HTML(相关部分)。
  • 推文按钮是否使用其他第三方脚本加载?
  • 我已经在推文按钮的标记中添加了一个指向 codepen 的链接。
  • @AtheistP3ace,我已经添加了代码笔,希望对您有所帮助。在 JS 部分,您可以看到我添加了一些来自 Twitter 的代码,以加载它们的小部件功能。

标签: javascript html domcontentloaded


【解决方案1】:

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

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

【讨论】:

  • 好的,我发现它确实比我想象的要多得多,包括插入一个巨大的 iframe 元素。在那之后尝试修改它要困难得多。
  • 是的,它实际上甚至没有保留原始锚的类。但它似乎继续拥有b 的ID。无论哪种方式,这里似乎都发生了很多事情。你可能想看看这个:dev.twitter.com/web/tweet-button
猜你喜欢
  • 2011-07-19
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
  • 2018-11-24
  • 2021-12-08
  • 2022-10-15
  • 2017-10-01
  • 2011-07-16
相关资源
最近更新 更多