简体   繁体   中英

How to change style of an element on another page using JavaScript or jQuery?

Ok, this is my problem... I have two pages. On the first page I have a header ( h2 ) element on which I want to apply a border style. On the second page, there is only one link. When clicking on the link from the second page, to navigate to the first page, it should create a border on the first page around the h2 tag.

Any thoughts on how to do this? Is it possible to do it with regular JavaScript or jQuery?

Thanks!

No , JavaScript is client-side and for this you would require the server to remember if the link was clicked, possibly by recording this in a database or session variable.

That's of course if you're using the tradition model of a website, rather than loading pages already using pure JS.

It would be a pretty stupid way of doing it, but it is possible to do it client side. I would seriously recommend to do it server-side though.

On page 2, link back to page 1 with a hash:

<a href="/page1#border">Go back to page one and add a border</a>

And on page 1, check if there's a hash:

if (window.location.hash === '#border') {
    $('h2').addClass('withBorder');
}

I think if you are looking this kind of scenario you can achieve it with passing some hash to the url:

i passed a hash named 'second' in the second page url and put this script on second page

$(function(){
    var url=window.location;
    var hash = url.hash.substr(1);
    if(hash == "second"){
       $('h2').css('border','solid 1px red');
    }
});

Checkout this if helps.

Well there is a way you could do this with JavaScript, although it's tricky and server side is a LOT easier. You would need to use some JavaScript to load different pages without refreshing the entire DOM. I do this with something called pjax . The way it works is to have each page act as a container to load all subsequent pages via ajax. By not doing a full page reload, any style changes you make on one page get carried over to other pages (this dose not survive an actual browser refresh).

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