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

1

你有没有尝试过?

var url = window.location.pathname;
var string = 'index.php';
if(url.indexOf(string) !== -1) {
   $j( ".nav li:nth-child(2)" ).addClass( "active" );
}
于 2013-09-20T09:17:52.977 回答
0

您可以使用以下内容: http: //api.jquery.com/contains-selector/

这允许您搜索特定的字符串(区分大小写)

于 2013-09-20T09:18:10.237 回答
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 回答