[英]JavaScript…Cannot call method match of undefined
我收到此錯誤: Uncaught TypeError: Cannot call method 'match' of undefined
在我的JavaScript中Uncaught TypeError: Cannot call method 'match' of undefined
。 我正在嘗試不使用jQuery編寫此代碼,因為它將是該網站上唯一的js。
我的代碼應該在鏈接到當前頁面的導航中的<a href="...>
中添加一個“active”類。
我猜它可能是contentLoaded
函數?.... 來源
這是我的代碼......(錯誤發生在第9行)... 小提琴
(function(window, document, undefined) { contentLoaded(window, function() {
var page = document.location.pathname.match(/[A-z]+$/)[0],
nav_anchors = document.getElementsByTagName('header')[0]
.getElementsByTagName('nav')[0]
.getElementsByTagName('a');
for(i in nav_anchors)
if(nav_anchors[i].href.match(/[A-z]+$/)[0] = page) //LINE 9 <-- Error
nav_anchors[i].classList.add('active');
})
})(this, this.document)
謝謝!
NodeLists
具有length
, item
和namedItem
屬性。
for (var i = 0; i < foo.length; i++)
不是for i in foo
迭代它們而只是命中節點。
(function(window, document, undefined) { contentLoaded(window, function() {
var page = document.location.pathname.match(/[A-z]+$/)[0],
nav_anchors = document.getElementsByTagName('header')[0]
.getElementsByTagName('nav')[0]
.getElementsByTagName('a');
for(var i=0;i<nav_anchors.length;i++)
if(typeof nav_anchors[i].href != "undefined" && nav_anchors[i].href.match(/[A-z]+$/)[0] == page)
nav_anchors[i].classList.add('active');
})
})(this, this.document)
增加了一個檢查,如果href
錨的設置,如果你有沒有HREF屬性(如頁面錨<a name="top">
使用#top返回調用)。 在IF
添加了第二個=
,以使其按預期工作。 並更正了for語法。
if(nav_anchors[i].href.match(/[A-z]+$/)[0] = page) //LINE 9 <-- Error
在javaScript中,equals sign =
是賦值運算符。 您可能是說double equals ==
,您可以在沒有類型強制的情況下檢查值( 5 == "5"
),而對於強類型檢查(其中5 !== "5"
),可以使用Triple equals ===
。
有時document.location.pathname.match(/[Az]+$/)
可以為null。 如果嘗試使用document.location.pathname.match(/[Az]+$/)[0]
,則無法訪問null的0元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.