jstree - 在页面启动时以编程方式在 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
});
解决方案
我在 Chrome 的控制台中看不到任何错误:
你的代码很好。只是树还没有准备好。如果您将现有代码包装在 ready.jstree 事件中,它将起作用。
$tree.on('ready.jstree', function (e, data) {
// Copy line 38 onward and place your existing code here
});
推荐阅读
- c# - Start process with QUARTZ.NET
- eclipse - getting following error on Adding org.glassfish.jersey.archetypes in eclipse version Oxygen
- ios - 从键值对数组创建一个键数组
- wpf - WPF Stackpanel Children unable to select using foreach
- regex - The cypher regex operator in neo4j is giving unexpected behavior
- php - Menu Drop-Down using MySQL enum in Laravel
- laravel - Run asynchronous code in laravel controller
- javascript - $_$wf is not defined wallaby.js and puppeteer interference
- java - Greek characters show as question marks or boxes when exporting from an old Access database
- file - How to copy a byte-range into a new output file in Rust?