使用Bootstrap treeview collapse / expand

时间:2016-09-23 23:52:42

标签: javascript jquery html twitter-bootstrap

我使用Twitter Bootstrap的treeview插件生成目录。我为每个节点提供的链接具有HTML所在的位置以及要转到的锚标记。我解析这个并在当前页面上的DIV中加载HTML,然后滚动到锚标记。使用下面的代码可以正常工作,但是当我折叠或展开节点时,它会停止在DIV中加载HTML并直接打开页面,基本上忽略了我对锚标记的点击事件。知道为什么不会触发点击事件?

我有以下代码来监听按钮我必须按如下方式展开或折叠整个树:

    var $treeview = $('#treeview');
    $("#expand").click(function (e) {
        e.preventDefault();
        $treeview.treeview('expandAll', { silent: true });
    });

    $("#collapse").click(function (e) {
        e.preventDefault();
        $treeview.treeview('collapseAll', { silent: true });
    });

我将silent设置为true以抑制事件,但是我的监听器将不再调用其中包含hrefs的锚标签。一切都按预期工作,否则我不确定为什么这些事件调用会导致这个问题。不幸的是,我无法使用nodeSelected事件,因为后续点击锚标记会导致其他HTML页面加载,这是不受欢迎的;它需要保留在当前页面上,因此以下代码是我能够实现的唯一方式。

    $("a[href*='#']").click(function(e) {
        e.preventDefault();            
        if (this && this.href !== "") {
            // Split location and hash
            var hash = this.hash;
            var location = this.href.match(/[^#]*/g)[0];

            $('#contents').load(location, function () {
                $('html, body').animate({
                    scrollTop: $(hash).offset().top - 55
                }, 200);
            });
        }
        return false;
    });

1 个答案:

答案 0 :(得分:1)

也许你可以这样做

$("body").on("click", "#expand", function (e) {
    e.preventDefault();
    $treeview.treeview('expandAll', { silent: true });
});

$("body").on("click", "#collapse", function (e) {
    e.preventDefault();
    $treeview.treeview('collapseAll', { silent: true });
});

$("body").on("click", "a[href*='#']",function(e) {
        e.preventDefault();            
        if (this && this.href !== "") {
            // Split location and hash
            var hash = this.hash;
            var location = this.href.match(/[^#]*/g)[0];

            $('#contents').load(location, function () {
                $('html, body').animate({
                    scrollTop: $(hash).offset().top - 55
                }, 200);
            });
        }
        return false;
    });