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>

2 番目と 3 番目の li 項目をクリックすると、うまく機能します。しかし、最初のアイテムをクリックしても、アイテムがアクティブになりません。何が間違っていて、その理由は何ですか?

4

2 に答える 2

0

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

への変更

if (current_page.match(/signature/)) {
于 2013-09-11T02:14:08.117 に答える
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 に答える