Search code examples
javascriptjqueryjqtree

Generate different event for both select node and delete icon in jqtree


following is my code :

var nodeData = ${jsonArray}; // my json data
$('#tree1')
            .tree(
                    {
                        data : nodeData,
                        autoOpen : 1,
                        onCreateLi : function(node, $li) {                              
                            $li
                                    .find('.jqtree-element')
                                    .append(
                                            '<a href="javascript:void(0);" class="delete" data-node-id="Test"><i class="ico ico-tool-delete"></i></a>');
                        }
                    });

    $('#tree1').bind('tree.click', function(event) {
        if (event.node) {               
            var node = event.node;
            alert("edit");

        }
        $tree.on('click', '.Test', function(e) {
            alert("delete");
        });
    });

I want to generate different event when click on node and delete icon.

Currently when I click on node and delete icon both generate same event.

Help me, which changes required in above code.

thanks


Solution

  • First you are trying to select elements with class Test but this class is not existing.

    Also the delete icon is inside the li nodes elements this is why you get the same event fired.

    Try to append the delete a element like this:

    $('#tree1').tree({
         data : nodeData,
         autoOpen : 1,
         onCreateLi : function(node, $li) {   
              $li.append(
                  '<a href="#" class="delete" data-node-id="Test"><i class="ico ico-tool-delete">Delete</i></a>');
              }
         });
    

    check fiddle

    Edit:

    you can save the node id as data attribute while appending the delete element. Then when you click on a specific delete element get the required node by id:

    var node = $tree.tree('getNodeById', $(this).data('parent-id'));
    

    Then remove this item:

    $tree.tree('removeNode', node);
    

    new fiddle