使用jquery创建hashtag url

时间:2012-09-08 13:27:34

标签: jquery hashtag

这是我的JSFiddle。我想将网址设为http://example.com/#content-1并在我点击下一步时更新为下一个h2标题。有什么帮助吗?

3 个答案:

答案 0 :(得分:5)

这是一个非常快速的解决方案,无需更改太多代码:

<强>的Javascript

$(".next").click(function(){
    var current = $('ul li.selected').index(),
        maxIndex = $('ul li').length - 1,
        next = (current + 1) >  maxIndex ? 0 : (current + 1);

    setActive(next);

    // gets text content wrapped in selected div's h2
    var titleText = $(".selected .sl-title").text(); 

    // replaces the space between "Content" and number with a "-" (dash)
    var hashTag = titleText.replace(/ /g, '-');

    // update url
    window.location.hash = hashTag;
});

~UPDATE01 090912~

OP问道,“你能告诉我即使刷新页面后如何获得相同的内容吗? - user1619228 1小时前”

您可以在function setActive(i) { // codes }

之后添加此权限
    // apply the following only if the word "Content" is present in URL
    if(url.indexOf('Content') != -1){ 

         // gets current hash value (fragment identifier) of URL
         var url = window.location.hash; 

         // removes the "#" symbol
         var currentHash = window.location.hash.substring(1).split("#"); 

         // replaces the "-" with a space
         var contentTitle = currentHash.toString().replace(/-/g, ' '); 

         // set text string in variable (to be used later)
         var actualContent = "This is " + contentTitle; 

         // remove "selected" class from all "myclass" divs
         $(".myclass").removeClass("selected"); 

         // add "selected" class to div that has the string stored in "actualContent" variable  
         $("div:contains('" + actualContent + "')").addClass('selected'); 
     }

上面的附加脚本只是:

  1. 检查网址以查看是否存在“内容”字样,如果是,请继续:
  2. 获取URL的哈希标记(片段标识符)
  3. 删除符号(#和 - )
  4. 将其作为文本字符串放入变量
  5. 运行整个文档以查找包含该文件的div 与变量相同的内容,或以间接的方式,与URL相同 主题标签
  6. 首先从所有div中删除“selected”类,然后添加它 返回包含与变量相同内容的div,或 以间接方式,URL的哈希标记(片段标识符)
  7. 我还没有解决图像背景颜色的更新问题,但我相信如果你应用上面演示的基础知识,你也可以将“选定”类添加到正确的图像中。当然,您需要通过向包含图像的列表项添加一些额外的ID或类来稍微调整代码,以便通过jQuery操作它们。

    我知道上面可能不是最漂亮或最好的解决方案,但是当我对自己施加限制而不是改变你的HTML结构或jQuery时,它是唯一想到的。

    希望这有助于进一步发展!

    UPDATE02 090912

    OP的进一步参考

    以下是整个文档的外观:

    整个文件

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Untitled Document</title>
    <script type="text/javascript" src=" https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js "></script>
    </head>
    <style>
        .myclass {
            display:none;
        }
    
        ul li {
            display: inline-block;
        }
    
        img {
            height: 20px;
            width: 20px;
            padding: 20px;
        }
    
        .myclass.selected {
            display: block;
        }
    
        ul li.selected {
            background-color: yellow;
        }
    
        ul li, .next {
            cursor: pointer;
        }
    </style>
    <body>
        <div class="myclass">
            <h2 class="sl-title">#Content 1</h2>
            This is Content 1
        </div>
        <div class="myclass">
            <h2 class="sl-title">#Content 2</h2>
            This is Content 2
        </div>
        <div class="myclass">
            <h2 class="sl-title">#Content 3</h2>
            This is Content 3
        </div>
        <ul>
          <li><img src="http://www.lillehammer.com/ImageVault/Images/id_2122/scope_66/ImageVaultHandler.aspx" /></li>
          <li><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/d/d7/Valued_image_seal.svg/40px-Valued_image_seal.svg.png" /></li>
          <li><img src="http://www.iconico.com/i/icoImageFilterPro100.gif" /></li>
        </ul>
        <a class="next">next</a>
    </body>
    <script type="text/javascript">
        $(document).ready(function(){
    
            setActive(0);
    
            $('li').click(function() {
                setActive($(this).index());
            });
    
            $(".next").click(function(){
                var current = $('ul li.selected').index(),
                    maxIndex = $('ul li').length - 1,
                    next = (current + 1) >  maxIndex ? 0 : (current + 1);
    
                setActive(next);
    
                // gets text content wrapped in selected div's h2
                var titleText = $(".selected .sl-title").text(); 
    
                // replaces the space between "Content" and number with a "-" (dash)
                var hashTag = titleText.replace(/ /g, '-');
    
                // update url
                window.location.hash = hashTag;
    
            });
    
            function setActive(i) {
                var li = $('ul li').eq(i);
    
                $('ul li').removeClass('selected');
                li.addClass('selected');
                $('.myclass').removeClass('selected');
                $('.myclass').eq(i).addClass('selected');
            }
    
            var url = window.location.hash; // retrieve current hash value (fragment identifier)
            if(url.indexOf('Content') != -1){ // do the following if URL's hash contains "Content"
                // remove "#" symbol from retrieved hash value (fragment identifier)
                var currentHash = window.location.hash.substring(1).split("#");
                // remove "-" symbol from retrieved hash value (fragment identifier)
                var contentTitle = currentHash.toString().replace(/-/g, ' ');
                // store hash value in "actualContent" variable
                var actualContent = "This is " + contentTitle;
                // remove "selected" for every instance of "myclass" to hide content first
                $(".myclass").removeClass("selected");
                // find div that contains retrieved hash value's (fragment identifier's) text stored in "actualContent" variable and add "selected" class to that div to display the correct content
                $("div:contains('" + actualContent + "')").addClass("selected");
            }
    
        });
    </script>
    </html>
    

    只需将所有内容复制并粘贴到新的HTML文件中,然后在您选择的浏览器中打开它,然后单击“下一步”并刷新。显示的页面内容应保持不变。复制新URL,打开一个新选项卡并将复制的URL扔到地址栏中 - 页面加载并根据哈希标记显示正确的内容。

答案 1 :(得分:2)

这应该有用,对吧?

function setActive(i) {
    var li = $('ul li').eq(i);

    $('ul li').removeClass('selected');
    li.addClass('selected');
    $('.myclass').removeClass('selected');
    $('.myclass').eq(i).addClass('selected');

    // add hashtag
    var selectedText = $('.myclass.selected h2').text();
    window.location.hash = selectedText;
}

答案 2 :(得分:0)

你可以使用jQuery历史/散列更改插件来做到这一点。 Like this one。谷歌一下。你会发现更多。

或者看到这个StackOverflow帖子:What's the best library to do a URL hash/history in JQuery?