如何将jquery对象传递给history.pushState
var data = { url: $(this).attr('href'), selector: $(this) };
history.pushState(data, 'foo', $(this).attr('href'));
当我这样做时,我收到一个错误:
组件返回失败代码:0x8000ffff (NS_ERROR_UNEXPECTED) [nsIDOMHistory.pushState]
如果我将选择器更改为字符串,则错误就会消失...... 但我需要 jQuery 对象,这样我就可以在“popstate”事件上触发单击它:s
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
历史状态中的数据必须是可序列化的。也就是说,它必须可以转换为 JSON。
$(this)
返回一个带有 DOM 节点的类似数组的对象,该对象无法转换为 JSON。您应该寻找一种不同的方式来完成您正在寻找的事情。请记住,推送状态只是有用的信息,并不意味着是规范的。如果用户无法通过在地址栏中复制并粘贴 URL 来获得完全相同的内容,那么就有问题了。
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:
扩展 Brian Nickel 和 GregL 的答案,你可以通过执行 $('#'+this.id).attr('href') 来解决这个问题......只要你按照我之前的两个人的建议来 ID DOM。
有时我只能通过以下方式得到我想要的结果:
它使我能够在 id-ing 方面更具创意,例如,我可以有
$('#'+this.id+'*locator*');
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:
and it allows me to be more creative with my id-ing where, for example, I could have
$('#'+this.id+'*locator*');
考虑将 ID 或其他唯一属性分配给 jQuery 对象表示的 DOM 节点,然后您可以将该 ID 的值作为可序列化的字符串存储在数据对象中。
如果元素没有唯一 ID,请考虑生成一个并将其添加到元素中。
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.