2

このエラーが発生します:Uncaught TypeError: Cannot call method 'match' of undefinedJavaScriptで。jQueryがサイトで唯一のjsになるので、これをjQueryなしで書き込もうとしています。

私のコードは<a href="...>、現在のページにリンクするナビゲーションのに「アクティブ」というクラスを追加することになっています。

関数かもしれないと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)

ありがとう!

4

4 に答える 4

5

NodeListslengthitemおよびnamedItemプロパティがあります。

それらを反復処理せず、ノードのみをヒットするためにfor (var i = 0; i < foo.length; i++)使用します。for i in foo

于 2012-11-15T15:45:57.160 に答える
2
(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)

hrefhref属性のないページアンカーがある場合(<a name="top">#topを使用して呼び出される場合など)に、アンカーのが設定されているかどうかのチェックを追加しました。期待どおりに機能するように=、に1秒を追加しました。IFそして、構文を修正しました。

于 2012-11-15T15:48:52.693 に答える
0
if(nav_anchors[i].href.match(/[A-z]+$/)[0] = page) //LINE 9 <-- Error

javaScriptでは、等号=は代入演算子です。==おそらく、型強制なしで値をチェックできる場合はdouble equals () 、強い型付きチェックの場合は5 == "5"triple equals (where )を意味します。===5 !== "5"

于 2012-11-15T15:54:38.557 に答える
0

document.location.pathname.match(/[A-z]+$/)nullになることもあります。使用しようとするとdocument.location.pathname.match(/[A-z]+$/)[0]、nullの0要素にアクセスできません。

于 2012-11-15T15:57:18.613 に答える