Trailing slash remove in www.mysite.com/#i-bc

2019-09-15 18:53发布

问题:

I want to go to a particular div on my home page itself when select on change event. I want result like www.mysite.com#i-bc but trailing slash added in between them like www.mysite.com/#i-bc. I want to remove that trailing slash using jquery or something else. here is my code:

Script:

$(function(){
    $('.toggle-view').on('change', function () {
        var url = $(this).val();
        if (url) {
            window.location.hash = url;
        }
        return false;
    });
});

My html is like this:

<select class="toggle-view">
    <option value="#i-bc">1</option>
    <option value="#i-st">2</option>
    <option value="#i-mm">3</option>
    <option value="#i-cc">4</option>
</select>

<div id="i-bc">some content here </div>
<div id="i-st">some content here </div>
<div id="i-mm">some content here </div>
<div id="i-cc">some content here </div>

Thanks InAdvance

回答1:

Try this,

$(function(){
    $('.toggle-view').on('change', function () {
        var url = $(this).val();
        if (url) {
           window.location.hash = url;
        }
        return false;
    });
});

window.location.hash is specifically used to play with hashed urls.



回答2:

Better use window.location.hash. Its better than href

<script>
    $(function(){
      $('.toggle-view').on('change', function () {
          var url = $(this).val();
          if (url) {
              window.location.hash = url;
                    }
          return false;
      });
    });
 </script>