加载到不同页面时记住 li 活动状态

Remember li active state when loading to different pages?

本文关键字:li 活动状态 加载      更新时间:2023-09-26

我在下面有我的代码:

    <ul id="profileList" class="nav nav-list">
        <li><a href="<?php echo base_url('user/signature')?>">修改个人签名档</a></li>
        <li><a href="<?php echo base_url('user/location')?>">修改个人居住地</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 项时,它们运行良好。但是当我单击第一项时,项目未变为活动状态。有什么问题,为什么?

in

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

更改为

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

据我所知,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');