0

我的代码如下:

    <ul id="profileList" class="nav nav-list">
        <li><a href="<?php echo base_url('user/signature')?>">修改个人签名档&lt;/a></li>
        <li><a href="<?php echo base_url('user/location')?>">修改个人居住地&lt;/a></li>
        <li><a href="<?php echo base_url('user/education')?>">修改个人学校专业</a></li>
    </ul>

还有这里的JS代码:

<script type="text/javascript">
$(document).ready(function() {

    // store url for current page as global variable
    current_page = document.location.href

    // apply selected states depending on current page
    if (current_page.index(/signature/)) {
        $("ul#profileList li:eq(0)").addClass('active');
    } else if (current_page.match(/location/)) {
        $("ul#profileList li:eq(1)").addClass('active');
    } else if (current_page.match(/education/)) {
        $("ul#profileList li:eq(2)").addClass('active');
    } else { // don't mark any nav links as selected
        $("ul#profileList li").removeClass('active');
    };

    });
</script>

当我单击第二个和第三个 li 项目时,它们运行良好。但是当我单击第一个项目时,该项目没有变为活动状态。出了什么问题,为什么?

4

2 回答 2

0

据我所知,String.prototype.index不存在。也许您想使用该indexOf方法。

if (current_page.indexOf('signature') !== -1) {}

另外,String.prototype.match如果您只想知道是否匹配,请不要使用该功能,请使用该RegExp.prototype.test功能。

if (/education/.test('education')) { /*matches*/ }

但是,在您的情况下,您可以使用该match方法,而不是丢弃匹配项,而是使用它对您有利:

var sections = ['signature', 'location', 'education'],
    match = document.location.href.match(new RegExp(sections.join('|'), 'i')),
    selectorSuffix = match? ':eq(' + sections.indexOf(match[0].toLowerCase()) + ')' : '';

$('ul#profileList li' + selectorSuffix)[(match? 'add' : 'remove') + 'Class']('active');
于 2013-09-11T02:50:32.883 回答
0

if (current_page.index(/signature/)) {

改成

if (current_page.match(/signature/)) {
于 2013-09-11T02:14:08.117 回答