[英]How do I get the id of the selected node in jsTree?
如何在jsTree中獲取所選節點的id?
function createNewNode() {
alert('test');
var tree = $.tree.reference("#basic_html");
selectedNodeId = xxxxxxxxx; //insert instruction to get id here
tree.create({ data : "New Node Name" }, selectedNodeId);
}
由於無法使用harpo的解決方案,並且不願意使用Olivier的解決方案,因為它使用內部的jsTree函數,我提出了一種不同的方法。
$('#tree').jstree('get_selected').attr('id')
就這么簡單。 get_selected
函數返回所選列表項的數組。 如果你對該數組執行.attr
,jQuery將查看列表中的第一項。 如果您需要多個選擇的ID,請將其視為數組。
jsTree中的節點基本上是包裝列表項。 這將為您提供第一個參考。
var n = $.tree.focused().get_node('li:eq(0)')
如果您有對樹的引用,則可以替換$.tree.focused()
。
要獲取id,請使用第一個匹配的元素
if (n.length)
id = n[0].id
或者您可以使用jQuery attr函數,該函數適用於集合中的第一個元素
id = n.attr('id');
在jstree
3.1.1
版中,您可以直接從get_selected
獲取它:
$("#<your tree container's id>").jstree("get_selected")
在最新版本的jsTree(在3.3.3中檢查)中,您可以執行此操作以獲取ID數組:
var ids = $('#tree').jstree('get_selected');
這將返回,例如, ["selected_id1", "selected_id2", "selected_id3"]
。 如果要獲取所選節點 (而不是ID),可以執行以下操作:
var nodes = $('#tree').jstree('get_selected', true);
當前的文檔包含更多信息。
$.jstree._reference('#my_tree_container')._get_node(null, true).each(function() {
id = $(this).attr("id");
alert('Id selected: ' + id);
});
我在使用MULTIPLE選擇從樹中獲取所選id時遇到問題。 這是我得到它們的方式:
var checked_ids = [];
$("#your-tree-id").jstree('get_selected').each(function(){
checked_ids.push($(this).data('id'));
});
就我而言,數據調用不起作用。 我成功通過使用attr函數訪問我的節點數據。
$("#tree").jstree("get_selected").attr("my-data-name");
獲取所有選定的ID使用以下代碼
var selectedData = [];
var selectedIndexes;
selectedIndexes = $("#jstree").jstree("get_selected", true);
jQuery.each(selectedIndexes, function (index, value) {
selectedData.push(selectedIndexes[index].id);
});
現在,您在“selectedData”變量中擁有所有選定的ID
隨着最新版本的Jstree; 你可以這樣做:
<script type="text/javascript>
var checked_ids = [];
$('#your-tree-id).jstree("get_checked",null,true).each(function(){
checked_ids.push(this.id);
});
alert(checked_ids.join(","));
</script>
<script type="text/javascript>
checked_ids.push($(this).context.id);
</script>
只是用
var nodeId = $('#FaqTreeView').jstree().get_selected("id")[0].id;
其中#FaqTreeView
是包含jstree的div的id。
在某些情況下和/或jstree版本中,此解決方案不起作用。
$('#tree').jstree('get_selected').attr('id');
而不是定義“id”我沒有得到什么。 對我來說訣竅是:
$("#tree").jstree("get_selected").toString();
這些都是舊版本的舊答案。 從版本3.3.3開始,這將獲得所選節點的所有屬性。
$('#jstree').jstree().get_selected(true)[0]
如果你想要id,那么最后添加.id。 如果復制上述代碼,則可以查看Web開發人員工具中的所有其他屬性。
您可以使用以下代碼var nodes = $(“#jstree_demo_div”)。jstree(true).get_selected(“full”,true); //所選節點的列表
nodes [0] .id //這將從數組中提供第一個對象的id
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.