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

时间:2015-12-11 09:55:38

标签: javascript

因此,我正在为网站撰写用户脚本,但我遇到此错误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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

您需要使用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>

答案 1 :(得分:0)

JavaScript中没有of运算符需要更改

for (var button of controlBar) {

for (var button in controlBar) {