0

この JQUERY 条件の論理構文を構築するのに助けが必要です。

現在の URL ウィンドウに特定の$string(index.php) が含まれている場合、特定の<li>クラスに値を追加したいと考えています。以下に示すように。

<ul class="nav">
  <li>...</li>
  <li>index</li>
</ul>

これがターゲット要素 ('.nav li:nth-child(2) ').addClass("selected")です。

これは私のjqueryです。私のロジックの正しい構文をコーディングする方法がよくわかりません。

 $j(function(){
    var url = window.location.pathname;
    var string = 'index.php';

    if //current url has $string ('index.php') {
     $j( ".nav li:nth-child(2)" ).addClass( "active" );
    });
 });
4

4 に答える 4

0

これは、リダイレクト ページとデフォルト ページのシナリオにwindow.location.pathは含まれないため、サーバー側で実行することをお勧めします。index.php

<script>からタグまたはグローバル設定変数をエコーするだけですindex.php

<!-- in index.php -->
<script type="text/javascript">
     Settings.isIndex = true;
</script>

そしてscript.jsで:

var Settings = { isIndex: false };

$j(function(){
    var url = window.location.pathname;
    var string = 'index.php';

    if (Settings.isIndex) {
      $j( ".nav li:nth-child(2)" ).addClass( "active" );
    });
});
于 2013-09-20T09:19:36.973 に答える
0

使用することもできます。

var url = window.location.pathname;
var your_string = 'index.php';

if(url.contains(your_string) === true ) {
    $j( ".nav li:nth-child(2)" ).addClass( "active" );
}

また

if(url.indexOf(your_string) !== -1) {
    $j( ".nav li:nth-child(2)" ).addClass( "active" );
}
于 2013-09-20T09:25:17.573 に答える