简体   繁体   中英

How to change a link's HREF using JavaScript?

I'm making a game, and I want to have something that the player can click to toggle the colors of the page. Specifically, I want to have the player be able to change the Bootstrap theme (following themes taken from Bootswatch) from Cerulean to Darkly to make the page style look different.

To do this I need to be able to change the HREF of the link using JavaScript. How would I do this exactly?

Since you're using twitter-bootstrap , I assume you're using jQuery . You can change a <link> 's href attribute with a simple call:

$("link[href=OLDHREFYOUWANTTOCHANGE]").attr("href", newURL.com)

However, I'm afraid this won't necessarily reload the CSS for the page. Maybe you can set a window.location.hash for the website (or some other parameter) and have a certain set of stylesheets load depending on that.

For example, at the top of your page:

<script>
    var hash = window.location.hash;
    if (hash === "#blue")
        //add blue stylesheet
    else
        //add red stylesheet
</script>

The easiest way to get it to work correctly is to simply reload the page and only load the specific css file as needed.

But you can add a new css file like this, not sure if it will work correctly in all cases since it won't reset your old css:

var link = $('<link>');
link.attr({
        type: 'text/css',
        rel: 'stylesheet',
        href: <your CSS file url>
});
$('head').append(link); 

如果您使用的是jQuery,请使用以下代码:

$(location).attr('href','http://www.newurlorwhatever.com'); 

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