保持锚标记href不会跳转到它的页面

时间:2016-09-19 22:39:44

标签: javascript jquery html twitter-bootstrap

我的HTML中有以下锚标记,用于将该HTML位置的内容加载到当前页面上的contents div中。这个锚标记是我用来生成目录的Bootstrap treeview插件的一部分:

<a href="/Introduction/index.html#1-1-overview1" style="color:inherit;">1.1 Overview</a>

在我的JavaScript中,我使用以下代码来监听两个事件。一个用于锚标记,以便我禁用默认行为,另一个用于处理锚标记并加载内容并滚动到锚点,如下所示:

    $("a[href*='#']").click(function(e) {
        e.preventDefault();
    });

    // Add smooth scrolling to all links inside a navbar
    $treeview.on('nodeSelected', function (e, data) {
        e.preventDefault();

        if (data && data.href !== "") {
            // Split location and hash
            var hash = data.href.match(/[#].*/g)[0];
            var location = data.href.match(/[^#]*/g)[0];

            if (prevLocation === location) {
                // Don't reload page if already at same location as last clicked
                $('html, body').animate({
                    scrollTop: $(hash).offset().top - 55
                }, 200);
            } else {
                prevLocation = location;
                $('#contents').load(location, function () {
                    $('html, body').animate({
                        scrollTop: $(hash).offset().top - 55
                    }, 200);
                });
            }

        }
        $body.scrollspy('refresh');
        $sideBar.affix('checkPosition');
    });

我所看到的是,第一次单击我的TOC中的节点时,它会按预期将HTML加载到内容div中,但是第二次单击它时,它会加载锚标记中引用的HTML页面尽管我努力跟踪我以前加载它是否像上面的条件逻辑一样。我还注意到,在随后的点击中,没有调用锚点选择器。

我知道如何让TOC最初将HTML从另一个页面加载到当前页面然后在后续调用中滚动到锚点位置(即章节)?

1 个答案:

答案 0 :(得分:0)

组合这两个函数并返回false似乎如下工作:

     $("a[href*='#']").click(function(e) {
        e.preventDefault();

        if (this && this.href !== "") {
            // Split location and hash
            var hash = this.href.match(/[#].*/g)[0];
            var location = this.href.match(/[^#]*/g)[0];

            if (prevLocation === location) {
                // Don't reload page if already at same location as last clicked
                $('html, body').animate({
                    scrollTop: $(hash).offset().top - 55
                }, 200);
            } else {
                prevLocation = location;
                $('#contents').load(location, function () {
                    $('html, body').animate({
                        scrollTop: $(hash).offset().top - 55
                    }, 200);
                });
            }

        }
        $body.scrollspy('refresh');
        $sideBar.affix('checkPosition');
        return false;
    });