简体   繁体   中英

How to pass jquery object to history.pushState

var data = { url: $(this).attr('href'), selector: $(this) };
history.pushState(data, 'foo', $(this).attr('href'));

When I do this I get a error:

Component returned failure code: 0x8000ffff (NS_ERROR_UNEXPECTED) [nsIDOMHistory.pushState]

If I change selector to a string, then the error goes away... But I need the jQuery object, so I can trigger click on it on the "popstate" event :s

The data in the history state must be serializable. That is, it must be convertible to JSON. $(this) returns an array-like object with DOM nodes which cannot be converted to JSON. You should look for a different way to do what you're looking for.

Remember, the push state is just helpful information and is not meant to be canonical. If the user can't get the exact same content by copying and pasting the URL in the address bar you've got a problem.

You can store a reference to a (un-serializable) rich Object and then retrive it by reference.

See a quick demo:

var historyStateReference = {
    url1:{/*richobj*/},
    url2:{/*richobj*/}    
}
var serializableObj = {
    richObjRef = "url1",
    //otherProps
}


// pushState with a simple serializable Object
history.pushState(serializableObj, null, "newPath");



// then later refrence it via history.state 
historyStateReference[history.state.richObjRef] ​

Consider assigning an ID or other unique attribute to the DOM node that is represented by the jQuery object, then you can just store the value of that ID in your data object as a string, which is serializable.

If the element doesn't have a unique ID, consider generating one and adding it to the element.

Expanding on both Brian Nickel's and GregL's answer, you can solve that by doing $('#'+this.id).attr('href') ... as long as you ID the DOM as suggested by both guys before me.

Sometimes I only get the result I want by:

var $this = $('#'+this.id); //.... before hand ... 

and it allows me to be more creative with my id-ing where, for example, I could have $('#'+this.id+'*locator*');

... id='abGGFather'
... id='abGFather'
... id='abFather'
... id='ab'

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