【问题标题】:Create hashtag url using jquery使用 jquery 创建主题标签 url
【发布时间】:2012-09-08 13:27:33
【问题描述】:

这是我的JSFiddle。我希望 url 为 http://example.com/#content-1 并在单击下一步时更新到下一个 h2 标题。有什么帮助吗?

【问题讨论】:

  • 离题:我在 10 多个问题中看到了该代码。
  • 你应该使用anchor linkswindow.onhashchange事件。
  • 是的,你是对的。但我在这个 stackoverflow 帖子中得到了这段代码。谢谢..

标签: jquery hashtag


【解决方案1】:

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

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. 检查 URL 以查看是否存在“内容”一词,如果存在则继续:
  2. 获取 URL 的哈希标签(片段标识符)
  3. 删除符号(# 和 -)
  4. 将其作为文本字符串放入变量中
  5. 遍历整个文档以查找包含 与变量相同的内容,或以间接方式,URL 的 标签
  6. 首先从所有 div 中删除“选定”类,然后添加它 返回包含与变量相同内容的 div,或 以间接方式,URL 的哈希标记(片段标识符)

我还没有解决图像背景颜色的更新问题,但我相信如果您应用上面演示的基础知识,您也可以将“选定”类添加到正确的图像中。您当然需要通过向保存图像的列表项添加一些额外的 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 放入地址栏中 - 页面加载并根据哈希标记显示正确的内容。

【讨论】:

  • 我已更新我的答案,以便您获得 www.domain.com/#content-1 而不是 www.domain.com/#content(space)1。后者并不是“内容”与其对应数字之间空间的最佳余弦。
  • 不客气。即使您已经接受了另一个答案,如果您能对此表示赞同,那就太好了=)
  • 你能告诉我刷新页面后如何获得相同的内容吗?
  • @user1619228 URL 的哈希或页面本身的内容相同?
  • 如果页面显示#content-2,如果我刷新它会进入初始状态,即#content-1。我想在刷新时保留#content-2。
【解决方案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;
}

【讨论】:

    【解决方案3】:

    您可以使用 jQuery 历史/哈希更改插件来做到这一点。 Like this one。去谷歌上查询。你会发现更多。

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

    【讨论】:

    • 我在谷歌上搜索了更多。我无法得到此代码的答案。这就是我在这里发帖的原因。
    猜你喜欢
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 2011-01-22
    相关资源
    最近更新 更多