尝试使用 jQuery 操作 CSS 样式



我在页面侧面有一个导航栏,想根据 GET 参数突出显示几个条目中的一个。

经过一番阅读,我得出了这个解决方案,但它似乎不起作用:

在.html:

<script type="text/javascript">
    $(document).ready(highlight_me());
</script>

JS函数:

function highlight_me() {
    // ensure all links have class 'regular'
    document.links.className = 'regular';
    // determine which link to highlight
    var id = 'home';
        switch (querystring('view')) {
            case "set":
                id = 'settings';
                break;
            case "mc":
                id = 'messages';
                break;
            default:
                id = 'home';
        }
    // highlight link
    document.getElementById(id).className = 'highlight';
}
function querystring(key) {
    // extract GET-value for key
    var re = new RegExp('(?:\?|&)' + key + '=(.*?)(?=&|$)', 'gi');
    var r = [], m;
    while ((m = re.exec(document.location.search)) != null) r[r.length] = m[1];
    return r;
}

CSS 类:

a, a.regular, a:visited {
    color: #f0ce96;
}
a:active, a:hover, a.highlight {
    text-decoration: underline;
    color: #ffeebb;
}

我很感激有一个提示,指出我在哪里出错,在这里。

调用 highlight_me 函数时,您没有传递 "id" 参数。

为什么需要id作为参数?您不会在函数内的任何地方使用它。打电话给querystring还不够吗?在这种情况下,您无需执行if(id.length)部分。默认情况下,将 id 设置为 'home',然后让 switch 语句相应地修改变量。

这就是我要说的:

function highlight_me() {
// ensure all links have class 'regular'
document.links.className = 'regular';
// Set id to home by default
var id = 'home';
    switch (querystring('view')) {
        case "set":
            id = 'settings';
            break;
        case "mc":
            id = 'messages';
            break;
        default:
            id = 'home';
    }
// highlight link
document.getElementById(id).className = 'highlight';
}

函数$(highlight_me());需要一个参数id调用此函数时不提供该参数。并将您的函数放入 document.ready .

 $(document).ready(function() {
   // put all your function here.
 });

最新更新