Uncaught TypeError: t.querySelectorAll is not a function when initialiazing Embedded Tweets

Uncaught TypeError: t.querySelectorAll is not a function when initialiazing Embedded Tweets

我正在使用来自 Twitter 的嵌入式推文 API。 如果我从页面加载中获得 html 降价,一切都会很好。 如果我使用稍后添加内容的选项并按 ID 加载推文,它也很有效:

twttr.widgets.load(
  document.getElementById("container")
);

这在此处的文档中:https://dev.twitter.com/web/javascript/initialization#init

但是如果我尝试使用 class 名称加载推文:

twttr.widgets.load(
  document.getElementsByClassName("containers")
);

我在 Twitter widget.js 中收到此错误:

Uncaught TypeError: t.querySelectorAll is not a function

如果我将元素组记录到控制台,我有一个合适的组:

我是不是做错了什么,或者这是 Twitter 小部件上的错误?

谢谢!

编辑:

截至 2015 年 7 月 28 日,getElementsByClassName 示例已从 Twitter 的文档中删除,这要归功于另一个 post 我在 Twitter 开发论坛上制作的

问题可能是因为 document.getElementsByClassName returns 一个 NodeList 类型不是真正的 javascript Array 对象。另一方面,widgets.load 需要单个元素或 Array 个元素。这导致 nodeList 被视为单个元素,并且库尝试对其调用 querySelectorAll,这不适用于 NodeList 类型。

一个解决方案是在将它传递给 widgets.load 时将该 nodeList 转换为一个真正的数组。

一种方式:

twttr.widgets.load(
  Array.prototype.slice.call(document.getElementsByClassName("containers"))
);

这是有效的,因为 NodeList 有一个 length 属性 并且是可索引的.

根据 Twitter 的文档,load() 不接受任何参数或接受单个元素。

Called without argument, widgets-js will search the entire document.body DOM tree for uninitialized widgets. For better performance, pass an HTMLElement object to restrict the search only to children of the element.

因为 getElementsByClassName returns 和 HTMLCollection,你不能直接传递它。相反,您可以像这样传递集合中的第一个元素

twttr.widgets.load(
  document.getElementsByClassName("containers")[0];
);