如何从此脚本中删除#字符?

时间:2012-11-01 11:29:25

标签: jquery

我正在使用脚本在页面之间执行ajax调用 我无法理解的是每个href点击的原因 浏览器当前位置更改为www.blabla / #index 看看下面的代码,我的目标是更改当前位置 没有“#”-www.blabla / index

的东西
$("document").ready(function() {

var hash = window.location.hash.substr(1);
var href = $('#tabs-bar li a').each(function(){
    var href = $(this).attr('href');
    if(hash==href.substr(0,href.length-5)){
        var toLoad = hash+'.html #content';
        $('#content').load(toLoad)
    }                                           
});

$('#tabs-bar li a').click(function(){

    var toLoad = $(this).attr('href')+' #content';
    /// $('#content').fadeOut('100');
    $('#content').empty();
    $('#load').remove();
    $('#profile-cv').addClass("loading");
    //$('#content').append('<div class="loading"></div>');

    setTimeout(function () { loadContent(); }, 1000);

    window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);

    function loadContent() {
        $('#profile-cv').load(toLoad,showNewContent())
    }
    function showNewContent() {
        $('#profile-cv').append(hideLoader());
    }
    function hideLoader() {
        $('#profile-cv').removeClass("loading");

    }
    return false;

});

});

2 个答案:

答案 0 :(得分:0)

您需要停止执行该事件的默认操作。

使用e.preventDefault();实现此目的 - e是回调函数的第一个参数:

$('#tabs-bar li a').click(function(e) {
    e.preventDefault();
    var toLoad = $(this).attr('href') + ' #content';
    ...
});

答案 1 :(得分:0)

您正在设置

window.location.hash = $(this).attr('href').substr(0,$(this).attr('href').length-5);

location.hash 始终添加“#”。

查看PJAX library,以便修改网址。

<强>更新

该库使用新的HTML5 history.pushState API。不幸的是,除了IE 10之外,它在任何IE中都不起作用。

This nice tutorial应该可以帮助您实施它。

如果您需要旧浏览器的后备解决方案,则可以使用PJAXhistory.js等库。