如何在R Shiny应用的JSTree中实现子节点继承父节点属性
解决R Shiny中JSTree子节点继承父节点属性的问题
修改思路
在拖拽生成子节点的回调逻辑中,不再仅生成带序号的文本节点,而是复制父节点的样式、状态、图标等核心属性,确保子节点和父节点样式一致。
修改后的完整代码
library(shiny) library(shinyWidgets) ui <- fluidPage( tags$head( tags$script(HTML(" $(document).ready(function() { $('#jstree').jstree({ 'core': { 'check_callback': true, 'data': [ { 'text': '父节点1', 'icon': 'glyphicon glyphicon-folder-open', 'state': {'opened': true}, 'li_attr': {'style': 'color: #2ecc71; font-weight: bold;'}, 'children': [] }, { 'text': '父节点2', 'icon': 'glyphicon glyphicon-file', 'state': {'opened': false}, 'li_attr': {'style': 'color: #3498db; font-style: italic;'}, 'children': [] } ] }, 'plugins': ['dnd', 'contextmenu'] }).on('create_node', function(e, data) { // 获取父节点的所有属性 var parentNode = data.parent; var parentAttrs = $('#jstree').jstree('get_node', parentNode); // 复制父节点的属性到新节点 var newNode = $('#jstree').jstree('get_node', data.node); newNode.icon = parentAttrs.icon; newNode.li_attr = parentAttrs.li_attr; newNode.a_attr = parentAttrs.a_attr; newNode.state = parentAttrs.state; // 更新节点文本为父节点文本+子节点序号(可自定义) var childCount = $('#jstree').jstree('get_children_dom', parentNode).length; newNode.text = parentAttrs.text + ' - 子节点' + childCount; // 刷新节点应用修改 $('#jstree').jstree('refresh_node', parentNode); }); }); ")) ), jstreeOutput("jstree") ) server <- function(input, output, session) { output$jstree <- renderJstree({ jstree() }) } shinyApp(ui, server)
关键代码解释
- 获取父节点属性:在
create_node事件回调中,通过$('#jstree').jstree('get_node', parentNode)获取父节点的完整属性集合,包括图标、样式、状态等。 - 复制属性到新节点:将父节点的
icon、li_attr、a_attr、state直接赋值给新生成的子节点,确保样式继承。 - 自定义子节点文本:根据父节点下的子节点数量生成有序的子节点文本,替换原代码中无意义的序号+字母组合。
- 刷新节点:调用
refresh_node方法让修改后的属性立即生效。
内容的提问来源于stack exchange,提问作者Shakeel Ahmad
相关产品推荐
相关产品推荐

