【问题标题】:How do I use jQuery to create a bookmark-able hash?如何使用 jQuery 创建可书签的哈希?
【发布时间】:2011-03-31 12:24:52
【问题描述】:

我有一个用作图片库的 URL。在这个 URL 上是一个拇指 div(为简洁起见,我只显示四个拇指):

 <div id="thumbs">
 <img src="graphics/thumbs/01.jpg" width="190" height="190" class="thumb objects" id="project01" />
 <img src="graphics/thumbs/08.jpg" width="190" height="190" class="thumb web" id="project08" />
 <img src="graphics/thumbs/14.jpg" width="190" height="190" class="thumb freehand" id="project14"/>
 <img src="graphics/thumbs/04.jpg" width="190" height="190" class="thumb freehand objects" id="project04" /></div>

还有一个名为#content的空div

<div id="content"></div>

还有一个隐藏的div,叫做#preload

 <div id="preload">
<span id="project01_content"><img src="graphics/010.jpg" /></span>
<span id="project02_content"><img src="graphics/022.jpg" /><img src="graphics/021.jpg" /><img src="graphics/023.jpg" /><img src="graphics/020.jpg" /></span>
<span id="project03_content"><img src="graphics/030.jpg" width="450" height="600" /><img src="graphics/031.jpg" width="450" height="600" /></span>
<span id="project04_content"><img src="graphics/040.jpg" width="775" height="600" /><img src="graphics/041.jpg" width="775" height="600" /></span></div>

我的 jQuery 使用点击缩略图的 ID 到 clone() 对应的 span 中的图像,并使用 html() 方法将它们放入 #content。它工作得很好。现在,我想回到mysite.com/#project01 并让#content 已经填满了Project 01。

我怎样才能给每张图片一个哈希 URL 来调用相同的 jQuery 状态?

【问题讨论】:

    标签: jquery html fragment-identifier browser-state


    【解决方案1】:

    您可以在页面加载后立即单击该拇指,并且您的当前代码应该执行,如下所示:

    $(function() {
      if(window.location.hash.indexOf('project') > -1)
        $(window.location.hash).click();
    });
    

    这使用window.location.hash property,在您的示例网址中将是"#project01"...所以它已经是#ID selector,我们只是检查它是否是我们关心的哈希,然后使用该选择器触发一个.click()。只需确保它在您当前的拇指点击处理程序绑定之后运行

    【讨论】:

      猜你喜欢
      • 2011-03-01
      • 2011-09-20
      • 2015-10-06
      • 2014-08-28
      • 2011-04-20
      • 2012-12-16
      • 2013-12-20
      • 1970-01-01
      • 2012-01-02
      相关资源
      最近更新 更多