【问题标题】:jstree get checked and unchecked nodesjstree 获取选中和未选中的节点
【发布时间】:2012-10-17 06:57:33
【问题描述】:

我想从我的 jstree 中获取 2 个单独的数组中的选中节点和未选中节点。

我见过.get_checked.get_unchecked 函数,但它们返回给我当前选中和未选中的所有节点。 (即如果一个节点未被选中并且我没有取消选中它,那么我仍然使用.get_unchecked 来获取它。我想防止这种情况发生)。我也准备对 api 进行重大更改。有什么路线吗?

我可以获取复选框的更改事件吗?我也尝试过change_state,但这仅适用于被点击的一个节点。

【问题讨论】:

  • 你能提供任何代码吗?请制作jsfiddle

标签: javascript jquery checkbox jstree


【解决方案1】:

据我所知,如果不重写 jstree 的复选框插件几乎是不可能的)来处理复选框的单个事件,因为它们只是在每个选中/取消选中事件重绘单击文件夹的所有父项和子项。

这里是简单的demo

一切都为我工作,

HTML

<div id="demo1" class="demo">
    <ul>
        <li id="phtml_1">
            <a href="#">Root node 1</a>
            <ul>
                <li id="phtml_2" class="jstree-checked">
                    <a href="#">Child node 1</a>
                </li>
                <li id="phtml_3">
                    <a href="#">A Child node 2</a>
                </li>
            </ul>
        </li>
        <li id="phtml_4">
            <a href="#">Root node 2</a>
             <ul>
                <li id="phtml_2" >
                    <a href="#">Child node 1</a>
                </li>
                <li id="phtml_3">
                    <a href="#">A Child node 2</a>
                </li>
            </ul>
        </li>
    </ul>
</div>​

JS

$(function() {
    var tree = $("#demo1").jstree({
        "plugins": ["themes", "html_data", "checkbox", "sort", "ui"]
    });
    tree.bind("open_node.jstree close_node.jstree check_node.jstree uncheck_node.jstree", function(e) {
        console.log("Event", e);
        console.log('Cheked:', tree.jstree('get_checked'));
        console.log('Uncheked:', tree.jstree('get_unchecked'));
    });
});​

【讨论】:

【解决方案2】:

这篇文章或其他帖子的答案都对我有用,但找到了一种扫描节点并维护一组未选中项的方法。

我的方法是首先迭代地获取所有节点的列表,然后我引用了来自 answer 的代码来获取节点列表(我自己的调整以递归地遍历整个树,因为 OP 没有进入嵌套级别,而且我只想要 ID)。

然后我得到了一个带有过滤功能的 li 标签,用于过滤所有已点击和未确定的项目,并在其上进行了一个 for 循环,在其中我从之前检索的主列表中删除了这些。

$("#getUnchecked").bind("click", function () {

  //get a list of all nodes in the entire tree recursively - function in fiddle.
  ids = get_jstree_order('#tree > ul');

  var selNodes = $('li').filter(function () {
      //Find nodes that have jstree-clicked - or clicked items and
      //Find nodes that are undetermined
      return $(this).children('a.jstree-clicked').length
          || $(this).children('a').children('i.jstree-undetermined').length;
  });
  selNodes.each(function () {
      //find the position of the checked or undetermined id 
      let pos = ids.indexOf(this.id);
      //remove it from the master list, as we are filtering it down to just the unchecked ones
      ids.splice(pos, 1);
  })

  console.log(ids);
});

有关工作示例,请在此处查看fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多