Create hashtag url using jquery

倾然丶 夕夏残阳落幕 提交于 2019-12-09 13:58:12

问题


Here is my JSFiddle. I want the url as http://example.com/#content-1 and update to next h2 title when i click next. Any help please ?


回答1:


Here's a really quick solution without changing too much of your codes:

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 has asked, "Can you tell me please how to get the same content even after refresh the page ? – user1619228 1 hour ago"

You can do this by adding this right after 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'); 
     }

The additional script above simply:

  1. Checks the URL to see if there is the word "Content" present, if so proceed with:
  2. Gets URL's hash tag (fragment identifier)
  3. Removes symbols (# and -)
  4. Places it as a text string into a variable
  5. Runs through the entire document to find for the div containing the same content as the variable, or in an indirect way, the URL's hashtag
  6. Removes the "selected" class from all divs first and then adds it back to the div that contains the same content as the variable, or in an indirect way, the URL's hash tag (fragment identifier)

I have not addressed the updating of the image's background colour yet, but I believe that if you apply the fundamentals demonstrated above, you'd be able to add the "selected" classes to the right images as well. You'd of course be required to tweak the codes a little by adding some additional IDs or classes to the list items holding the images in order to manipulate them via jQuery.

I know the above may not be the prettiest or the best of solutions, but it's the only one that came to mind when I imposed a restriction on myself not to change too much of your HTML structure or jQuery.

Hope this helps further!

UPDATE02 090912

Further reference for OP

Here's how the whole document should look like:

WHOLE DOCUMENT

<!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>

Just copy and paste everything into a new HTML file and open it up in a browser of your choice, click on next and refresh. The page content that is shown should remain the same. Copy the new URL, open up a new tab and throw the copied URL into the address bar - the page loads and shows the correct content based on the hash tag.




回答2:


This should work, right?

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:


You can do that with a jQuery history/hash change plugin. Like this one. Google it. You will find many more.

Or see this StackOverflow post: What's the best library to do a URL hash/history in JQuery?



来源:https://stackoverflow.com/questions/12331132/create-hashtag-url-using-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!