首页 > 解决方案 > 在页面启动时以编程方式在 jsTree 中选择节点的问题

问题描述

我无法在页面启动时选择树元素。设置中有一个 JSFiddle:https ://jsfiddle.net/voltel/aszn3h46/

我的数据是 JSON 数组:


    const a_data = [
      {
        "id": "1296",
        "text": "Disposable and Single-Use Medical Supplies",
        "children": null
      },
      {
        "id": "1275",
        "text": "Implantables",
        "children": [
          {
            "id": "1276",
            "text": "Defibrillators, Implantable",
            "children": null
          },
          {
            "id": "1338",
            "text": "Analysers, Laboratory In-Vitro Diagnostic, Clinical Chemistry, Manual",
            "children": null
          },
        ]}  
    ];

    // Rest of JavaScript code 

    const $tree = $("#display");

    $tree.jstree({
      'plugins' : [ "wholerow", "checkbox" ],
      'core': {
        data : a_data
      },
      'checkbox': {
        three_state: false
      },
    });
    //

    // The problem: I can't select/check node with this id
    const c_icd_device_type = "1338";

    // show initial value
    if (c_icd_device_type) {
      console.log(`Request to select node with id ${c_icd_device_type}`);

      const o_selected_node = $tree.jstree('get_node', c_icd_device_type);
      console.log('Selected node: ', o_selected_node);

        // Uncomment ONE of the following: 
      if (o_selected_node) {
        $tree.jstree('select_node', o_selected_node, true);
      } else {
          $tree.jstree(true).select_node(c_icd_device_type);
      }//endif
    }//endif

请帮助在启动时选择一个节点,并消除控制台中的一些可疑错误(请参阅 JSFiddle)。

现在,我从 StackOverflow 上关于 jsTree 的其他问题了解到,如果将我的代码包装在事件处理程序中选择一个元素,它就可以工作。如果没有异步调用,我不太明白为什么它如此复杂。如果这是不可避免的,为什么不使用 Promise?

$tree.on('ready.jstree', function (e, data) {
  console.log(`Request to select node with id ${c_icd_device_type}`);

  const o_selected_node = data.instance.get_node(c_icd_device_type);
  //const o_selected_node = $tree.jstree('get_node', c_icd_device_type);

  console.log('Selected node: ', o_selected_node);

    // Uncomment ONE of the following: 
  if (o_selected_node) {
    $tree.jstree('select_node', o_selected_node, true);
  } else {
      $tree.jstree(true).select_node(c_icd_device_type);
  }//endif

});

标签: jstree

解决方案


我在 Chrome 的控制台中看不到任何错误:

你的代码很好。只是树还没有准备好。如果您将现有代码包装在 ready.jstree 事件中,它将起作用。

$tree.on('ready.jstree', function (e, data) {

    // Copy line 38 onward and place your existing code here

});

推荐阅读