当使用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以抑制事件,但随后我的锚标记侦听器将不再被调用。一切工作如预期,否则,所以我不确定为什么这些事件调用导致这个问题。不幸的是,我不能使用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;
    });

也许你可以这样做

$("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;
    });

最新更新