jquery 自定义函数调用无效

jquery custom function call not working

我是 jquery、ajax 和 jstree 的新手。我正在使用 jstree 使我的 <ul> 元素看起来像树结构。 我在 id = "container" 的 div 标签下有 <ul>。当我执行 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>

树结构显示正常。

我正在尝试编写一个 jquery 函数来获取 li 元素的名称作为参数。 例如:当我点击 Parent 时,该函数应该接收 "Parent" 作为参数,或者当我点击 child2-3 时,该函数应该得到 "child2-3" 作为参数。

我试图创建该功能,但它似乎不起作用。这是我的尝试 -

$("#treeNodes li").click(function() {  
   console.log("hello"); 
   console.log(this.innerHTML);
});

控件似乎转到了调用jstree() 的函数,但另一个函数似乎不起作用。 任何帮助或提示将不胜感激。提前致谢。

将您的结构变成 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>

我已经阅读了 jstree 页面的文档:https://www.jstree.com/

jstree 中有一个名为 jstree-children 的 class,从那个 class 你可以从列表中获取值,如下所示:

$(document).on('click', '.jstree-children ul li', function (e) { 
console.log($(this).html());
});

试试这个:https://jsfiddle.net/Mantixd/0jwpz2r1/