简体   繁体   English

尝试使用jQuery操作CSS样式

[英]Trying to manipulate CSS style with jQuery

I have a navigation bar at the side of a page and want to highlight one of several entries depending on GET-parameters. 我在页面的一侧有一个导航栏,并希望根据GET参数突出显示几个条目之一。

After a little Reading I came to this solution, but it does not seem to work: 经过一番阅读后,我得出了这个解决方案,但是它似乎不起作用:

in the .html: 在.html中:

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

the JS functions: 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;
}

the CSS classes: CSS类:

a, a.regular, a:visited {
    color: #f0ce96;
}

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

I'd be thankful for a hint that points me to where I go wrong, here. 我会很高兴收到一个提示,指出我在这里出了问题。

调用Highlight_me函数时,您没有传递“ id”参数。

Any reason why you need id as a parameter? 为什么需要id作为参数? You're not using it anywhere inside the function. 您不在函数内部的任何地方使用它。 Shouldn't a call to querystring be enough? 调用querystring应该不够吗? In that case, you don't need to do the if(id.length) part. 在这种情况下,您不需要执行if(id.length)部分。 Set id to 'home' by default, and then have the switch statement to modify the variable accordingly. 默认情况下,将id设置为'home' ,然后使用switch语句相应地修改变量。

Here's what I'm talking about: 这就是我在说的:

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';
}

function $(highlight_me()); 函数$(highlight_me()); want a parameter id which is not supply when you call this function.And put your function inside document.ready . 想要一个在调用此函数时不提供的参数id ,并将函数放入document.ready

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM