在 jsTree 中,使节点文本可单击的最佳方法是什么(用于选中复选框)

In jsTree, what's the best way to make the node text clickable (for checking the checkbox)

本文关键字:是什么 用于 方法 复选框 最佳 单击 jsTree 节点 文本      更新时间:2023-09-26

当单击复选框旁边的节点文本时,我希望复选框切换其选中状态。通常这是通过<label for="whatever"></label>完成的。但是由于 jsTree 不使用真正的复选框,那么如何做到这一点呢?

使用 $('#mytree').jstree({'plugins':['checkbox']}) 创建树时,如果我把.delegate("a", "click", function (event, data) { $(event.target).find('.jstree-checkbox').click() })放在最后,它就可以工作了。但有一个明显的延迟。

因此,我提出一个问题,单击其相应文本时选中该框的最佳方法是什么?

我同意你正在使用的点击处理程序技术。我没有看到提到的延迟,但这可能是因为我没有将任何内容发布回服务器。

如果复选框是纯可视的,那么也许可以直接修改类。这应该比抛出另一个点击事件更快。

$(event.target).parent("li:first").toggleClass("jstree-unchecked").toggleClass("jstree-checked");

jstree 的复选框插件在选中/取消选中节点时确实会执行其他操作。我相信以下内容应该可以满足您的需求:

$(function(){
    // Initialize jstree
    var $tree = $('.tree-target').jstree({
        "plugins": ["checkbox"]
    });
    // Bind an event to the anchor tag within each tree entry
    // Note: '.on' is used here as this will ensure that any
    // dynamically-generated entries will also use this 'click'
    // event.
    $tree.on('click', 'li.tree > a', function (e) {
        e.stopPropagation();
        // Find the first parent 'tree' element
        var $node = $(this).parents('li.tree').eq(0);
        // Toggle the state of the current 'tree' element
        // Note: The third parameter (in this case 'toggle')
        // can be any value other than true or false
        $tree.jstree('change_state', $node, 'toggle');
        return false;
    });
});​

附带说明一下,我相信您的方法导致重大延迟的原因可能与您将click事件绑定到页面上的每个<a/>标签有关。在尝试查找适当的事件目标时,这将导致大量开销。

相关文章: