简体   繁体   中英

How to switch between specific CSS files using jQuery?

For switching themes I use the script below which places a cookie and selects a specific CSS file.

if($.cookie("css")) {
    $("link").attr("href",$.cookie("css"));
}
$(document).ready(function() { 
    $("#layout li a").click(function() { 
        $("link").attr("href",$(this).attr('rel'));
        $.cookie("css",$(this).attr('rel'), {expires: 365, path: '/'});
        return false;
    });
});

In combination with these links:

<ul id="layout" class="PanelInfo">
    <li><a href="#" rel="/themes/bootstrap/design/style.css">Default style</a></li>
    <li><a href="#" rel="/themes/bootstrap/design/custom_bootstrap.css">Bootstrap</a></li>
    <li><a href="#" rel="/themes/bootstrap/design/custom_cerulean.css">Cerulean</a></li>
    <li><a href="#" rel="/themes/bootstrap/design/custom_cosmo.css">Cosmo</a></li>
</ul>

The problem is that it loads only one CSS file at all. It should switch only in a couple of CSS files, let's say: style.css , custom_bootstrap.css , custom_cerulean.css and custom_cosmo.css

All other CSS files shouldn't be changed. The situation now is that it disables all other CSS files. How can I achieve this using my script?

It's not completely clear from the question, but I'm guessing you've got several

`<link href="....`

elements on your page? One containing the one where you want to switch the values, and some others which should not be changed?

If so, then I think your problem is that your jQuery selector is selecting ALL the "link" element on your page and amending the URL in all of them to the same thing:

$("link").attr("href",$(this).attr('rel'));

Instead you need to select the specific id of the link you want to change, something like this:

$("#SwitchLink").attr("href",$(this).attr('rel'));

where SwitchLink is the id of specific a <link> element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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