如何防止子div中锚点的链接影响主URL?

时间:2014-11-10 02:06:23

标签: javascript jquery html

请考虑以下代码段:

<div id="help"></div> 
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
    var loadPage = function (){
        $("#help").load("http://localhost:3000/manual.html");
    }
    onload=loadPage;
</script>

这存在于我的主页上:

http://localhost:3000/

上面的代码工作正常并加载我的手册页。但是如果我在manual.html中点击这样的链接:

<a href='#introduction'>Introduction</a>

然后帮助div中的页面跳转到#introduction部分,但是我的浏览器中的url更新为:

http://localhost:3000/#introduction

这是没有意义的,因为#introduction锚只存在于manual.html中,如何防止#help div中的链接影响浏览器中的地址栏?

3 个答案:

答案 0 :(得分:1)

试试这个

$('a').click(function(e) {
    e.preventDefault();
    $("#help").load($(this).attr('href'));
})

答案 1 :(得分:1)

使用offsetpreventDefault

$('a').click(function(e) {
     // Go to '#introduction'
     var targetId = $(this).attr('href');
     $('html, body').offset({ top: $(targetId).offset().top, left: 0 });
     // this prevent 'http://localhost:3000/#introduction'
     e.preventDefault();
});

请参阅this post

答案 2 :(得分:0)

我已经有了一个可以将#help窗口滚动到标题的函数,当你单击父对象时,它会滚动到帮助窗口中的相关部分:

var moveTo = function(destination){
    //position of the top of the help window - does not change.
    var helpWindow = $("#help").offset().top;                  
    //difference between current scroll position and target position.     
    var relativeDistance = $(destination).position().top - helpWindow; 
     //add the distance from current position to the top to get distance to target from top
    var absoluteDistance = relativeDistance+ $("#help").scrollTop();            

    $("#help").animate({
        scrollTop: absoluteDistance
    }, 1000);
}

使用e.preventDefault()我能够使用此功能来做我想要的。 对于走在这条道路上的其他人来说,还有另外两件小事需要考虑。 首先,确保将.click()函数嵌套在页面加载的回调中,因为超链接在页面加载之前不会存在。其次,你可能想要使用一个子选择器,例如$(&#39; #help a&#39;)。click()以确保你只改变孩子内部链接的行为。

$("#help").load("http://localhost:3000/manual.html", function(){
    $('#help a').click(function(e) {
        e.preventDefault();                     //suppress standard link functionality
        moveTo($(this).attr('href'));           //scroll to link instead.
    })        
});