javascript/jQueryの新機能で、ページのURL が一致しない場合、要素にCSSクラスを追加しようとしています 3つの弦。私はこれらの行のコードを動作させることはできません。window.location.hrefが特定の文字列と一致しない場合、要素にCSSクラスを追加します。
if (window.location.href.match(/(interests|ideas|art)/) > -1) {
jQuery("#nav-about").addClass('active');
}
私の構文は間違っていますか?
EDIT:
それは誰もが私が作業しなければならない与えられた答えのように思えるが、彼らはありません。たぶん、私のコードの他の行が矛盾している:
$(document).ready(function() {
if (window.location.href.search(/(interests|ideas|art)/) > -1) {
jQuery("#nav-about").addClass('active');
}
if (window.location.href.match(/(interests)/) != null) {
jQuery("#nav-interests").addClass('active');
}
if (window.location.href.match(/(ideas)/) != null) {
jQuery("#nav-ideas").addClass('active');
}
if (window.location.href.match(/(art)/) != null) {
jQuery("#nav-art").addClass('active');
}
});
私のサイトはbenxd.meです。このメインページのリンク#nav-about
は、クラスactive
が必要です。このページではスクリプトは機能しません。他のページ、興味、アイデア、写真撮影のスクリプト。
'match()=== null'も正しく動作します。 – moped
@moped、はい。同様に動作しますが、 '.match()'が文字列全体を検索し、最初の一致位置で停止するのではなく、より多くの情報を持つ配列を返します(一致が見つかった場合) )。 – Makyen