开发者问题收集

未捕获的 TypeError:不是 Chrome 中的函数

2015-12-11
2909

因此,我正在为网站编写用户脚本,并遇到了此错误 Uncaught TypeError: is not a function 它不会在 Firefox 中发生,但会在 Chrome 中发生。我花了一个小时进行调试,但没有成功。

我提供了以下相关代码片段以在 Chrome 中重现错误。该脚本应该找到包含文本“下载”的按钮并返回 href。

function getSubmissionSource(){
  var controlBar = document.getElementsByClassName("button submission rounded");
  for (var button of controlBar) { //errors here
    var link = button.getElementsByTagName("a")[0];
    if (link !== undefined && link.textContent == "Download") {
      return link.href;
    }
  }
}
console.log(getSubmissionSource());
<div id="test"">
  <span class="button submission rounded">
    <a href="/view/18251152/" class="prev dotted">Older</a>
  </span>
  <span class="button submission rounded">
    <a href="">-Remove from Favorites</a>
  </span>
  <span class="button submission rounded">
    <a href="">Download</a>
  </span>
  <span class="button submission rounded">
    <a href="">Note user</a></span>
  <span class="button submission rounded">
    <a href="/view/18385008/">Newer</a>
    </span>
</div>
2个回答

您需要使用 for 循环来遍历 nodelist

function getSubmissionSource(){
  var controlBar = document.getElementsByClassName("button submission rounded");
  for (var i=0,iLen=controlBar.length;i<iLen; i++) { //errors here
    var link = controlBar[i].getElementsByTagName("a")[0];
    if (link !== undefined && link.textContent == "Download") {
      return link.href;
    }
  }
}
console.log(getSubmissionSource());
<div id="test"">
  <span class="button submission rounded">
    <a href="/view/18251152/" class="prev dotted">Older</a>
  </span>
  <span class="button submission rounded">
    <a href="">-Remove from Favorites</a>
  </span>
  <span class="button submission rounded">
    <a href="">Download</a>
  </span>
  <span class="button submission rounded">
    <a href="">Note user</a></span>
  <span class="button submission rounded">
    <a href="/view/18385008/">Newer</a>
    </span>
</div>
Rayon
2015-12-11

JavaScript 中没有 of 运算符,您需要将

for (var button of controlBar) {

更改为

for (var button in controlBar) {
Robert
2015-12-11