我是jquery,ajax和jstree的新手。我正在使用jstree使我的<ul>
元素看起来像树结构。
我在{= {container“}的<ul>
标签下有div
。当我执行html文件时,将div(id =“ container”)传递给jstree函数,如下所示:
$(function() {
$('#container').jstree();
});
我的html代码段如下:
<div id="container">
<ul id = "treeNodes">
<li>Parent
<ul>
<li>Child1
<ul>
<li>child2-1</li>
<li>child2-2</li>
<li>child2-3</li>
<li>child2-4</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
树状结构显示良好。
我正在尝试编写一个获取 li 元素名称作为参数的jquery函数。 例如:当我单击 Parent 时,该函数应将“ Parent”作为参数,或者当我单击 child2-3 时,该函数应将“ child2-3”作为论据。
我试图创建该功能,但似乎不起作用。这是我的尝试-
$("#treeNodes li").click(function() {
console.log("hello");
console.log(this.innerHTML);
});
该控件似乎转到了调用jstree()的函数,但另一个函数似乎不起作用。 任何帮助或提示,将不胜感激。提前致谢。
答案 0 :(得分:0)
将结构放入JSTree会创建新的HTML,并且这些新元素具有自定义类和新API。因此,您必须阅读文档以了解如何使用新结构。
如果您查看 this documentation page ,您将看到一个示例,该示例取决于自定义changed
事件。我已经复制了该示例,并为您的HTML和console
输出对其进行了自定义。
$(function() {
$('#container')
// listen for the custom "changed" event on any jstree
.on('changed.jstree', function (e, data) {
// When you click on a JSTree the event appears to fire on the entire tree
// You'll have to iterate the tree nodes for the selected one.
var i, j, r = [];
for(i = 0, j = data.selected.length; i < j; i++) {
r.push(data.instance.get_node(data.selected[i]).text);
}
console.clear();
console.log('Selected: ' + r.join(', '));
})
// create the instance
.jstree();
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.5/jstree.min.js"></script>
<div id="container">
<ul id = "treeNodes">
<li>Parent
<ul>
<li>Child1
<ul>
<li>child2-1</li>
<li>child2-2</li>
<li>child2-3</li>
<li>child2-4</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
答案 1 :(得分:-1)
我已经从jstree页面中阅读了文档:https://www.jstree.com/
jstree中有一个名为jstree-children的类,您可以从该类中从列表中获取值,如下所示:
$(document).on('click', '.jstree-children ul li', function (e) {
console.log($(this).html());
});