简体   繁体   中英

How can I fix this JQuery function to obtain the data-value value of the parent li element of a clicked element?

I am not so into JavaScript and JQuery and I am finding the following difficulties.

Into a page there is redered a tree (using the JQuery **JStree* library).

So into my view code I have something like this representing a node of this tree:

<li role="treeitem" data-jstree="{&quot;opened&quot;:true,&quot;selected&quot;:true,&quot;icon&quot;:&quot;/_layouts/15/images/ArxeiaProtocollo/Default/Titolario/tag.png&quot;}" data-id="1" data-value="6.1" aria-selected="true" aria-level="3" aria-labelledby="j1_5_anchor" aria-expanded="true" id="j1_5" class="jstree-node  jstree-open">
    <i class="jstree-icon jstree-ocl" role="presentation"/>
    <a class="jstree-anchor  jstree-clicked" href="#" tabindex="-1" id="j1_5_anchor">
        <i class="jstree-icon jstree-themeicon jstree-themeicon-custom" role="presentation" style="background-image: url(&quot;/_layouts/15/images/ArxeiaProtocollo/Default/Titolario/tag.png&quot;); background-position: center center; background-size: auto;"/>6.1 - Listino Prezzi</a>
    <ul role="group" class="jstree-children">
        <li role="treeitem" data-jstree="{&quot;opened&quot;:false,&quot;icon&quot;:&quot;/_layouts/15/images/ArxeiaProtocollo/Default/Titolario/tag.png&quot;}" data-id="1" data-value="6.1.1" aria-selected="false" aria-level="4" aria-labelledby="j1_6_anchor" id="j1_6" class="jstree-node  jstree-leaf">
            <i class="jstree-icon jstree-ocl" role="presentation"/>
            <a class="jstree-anchor" href="#" tabindex="-1" id="j1_6_anchor">
                <i class="jstree-icon jstree-themeicon jstree-themeicon-custom" role="presentation" style="background-image: url(&quot;/_layouts/15/images/ArxeiaProtocollo/Default/Titolario/tag.png&quot;); background-position: center center; background-size: auto;"/>6.1.1 - Acquisti - AAA</a>
        </li>
        <li role="treeitem" data-jstree="{&quot;opened&quot;:false,&quot;icon&quot;:&quot;/_layouts/15/images/ArxeiaProtocollo/Default/Titolario/tag.png&quot;}" data-id="0" data-value="6.1.0" aria-selected="false" aria-level="4" aria-labelledby="j1_7_anchor" id="j1_7" class="jstree-node  jstree-leaf jstree-last">
            <i class="jstree-icon jstree-ocl" role="presentation"/>
            <a class="jstree-anchor" href="#" tabindex="-1" id="j1_7_anchor">
                <i class="jstree-icon jstree-themeicon jstree-themeicon-custom" role="presentation" style="background-image: url(&quot;/_layouts/15/images/ArxeiaProtocollo/Default/Titolario/tag.png&quot;); background-position: center center; background-size: auto;"/>6.1.0 - Acquisti - ZZZ</a>
        </li>
    </ul>
</li>

So this is the script that render the tree using the JSTree JQuery library (it works perfectly fine):

<script>
$(function () { 
    $(#tree).jstree(
    { 
        "search" : { 
            "show_only_matches" : false 
        },        
        "plugins" : ["search"] 
    }
}).delegate("a", "click", function (event, data) {
    var pNode = event.target.parentNode.innerText;
    pNode = pNode.split(" - ")[0];

    // MY NEW CODE START
    var pNodeDataValue = event.target.parentNode.data('value');
    alert(pNodeDataValue);
    // MY NEW CODE END

    window.location.replace('" + link + "' + pNode); });
    var to = false; 
    $('#tree_q').keyup(function () { 
        if(to) { clearTimeout(to); } 
        to = setTimeout(function () { 
            var v = $('#tree_q').val(); 
            $('#tree').jstree(true).search(v); 
        }, 250); 
    }); 
}); 
</script>

As you can see this code contains also a delegate defining a function that handles the click on a specific tree node and here I am finding some difficulties trying to implement a litle change on the original logic.

The original logic that I am trying to change is the following one: clicking on a node should mean click on the element in the previous HTML code. So clicking on the an element it retrieve

var pNode = event.target.parentNode.innerText;
pNode = pNode.split(" - ")[0];

This code should do the following operation:

obtain the content of the clicked element and put it into the pNode variable. So pNode will contains something like this: 6.1 - Listino Prezzi (referring to the previous HTML code example), then split and put into pNode only the 6.1 value.

Ok it works fine but since I have to remove this index number (6.1 ans similar) from my tree visualization I have to obtain this value from somewhere else.

So I know that the data-value field of the parent

  • element. Infact as you can see in the previous HTML example code I have something like:

     <li role="treeitem" data-jstree="{&quot;opened&quot;:true,&quot;selected&quot;:true,&quot;icon&quot;:&quot;/_layouts/15/images/ArxeiaProtocollo/Default/Titolario/tag.png&quot;}" data-id="1" data-value="6.1" aria-selected="true" aria-level="3" aria-labelledby="j1_5_anchor" aria-expanded="true" id="j1_5" class="jstree-node jstree-open"> 

    As you can see there is data-value="6.1" and it is the value that I have to retrieve and then use in my function.

    As you can see into my previous JQuery code I tried to obtain it in this way:

     // MY NEW CODE START var pNodeDataValue = event.target.parentNode.data('value'); alert(pNodeDataValue); // MY NEW CODE END 

    but it is not working and in the console of my browser I am obtaining the following error message executing this line:

     TypeError: event.target.parentNode.data is not a function 

    Why? What is wrong? What am I missing? How can I try to fix this issue and obtain the value of the value of the data-value of the parent

  • element?

  • The problem is that you are mixing jQuery and plain javascript in the same code. The data() function, for example, it only works with jQuery selectors.


    First of all, let's choose the selector.
    With jQuery you have some ways to do so:

    1. Using the plain javascript you were using as reference: $(event.target.parentNode)
    2. Using this to not rerun the DOM query, and adding the parent() : $(this).parent() ;
    3. Using the plain javascript with parent() : $(event.target).parent()
    4. Using this.parentNode as reference: $(this.parentNode)

    Now, about getting the attribute data-value , with jQuery references, you can use these methods:

    1. Using data() to get data-* attributes: $(this).parent().data('value')
    2. Using attr() to get any attribute: $(this).parent().attr('data-value')

    But, if you realy want to use plain javascript references (I don't recommend it, since you already have jQuery), you can use javascript getAttribute() : event.target.parentNode.getAttribute('data-value')


    Snippet with examples:

     $("#clickable").on("click", function(event, data){ console.log("With jQuery: ", "\\n$(event.target.parentNode).data('value') :", $(event.target.parentNode).data('value'), "\\n$(this.parentNode).data('value') :", $(this.parentNode).data('value'), "\\n$(event.target).parent().data('value') :", $(event.target).parent().data('value'), "\\n$(this).parent().data('value') :", $(this).parent().data('value'), "\\n$(this).parent().attr('data-value') :", $(this).parent().attr('data-value'), "\\n\\nWith plain Javascript:", "\\nthis.parentNode.getAttribute('data-value')", this.parentNode.getAttribute('data-value'), "\\nevent.target.parentNode.getAttribute('data-value') :", event.target.parentNode.getAttribute('data-value')); }); 
     #clickable { border: 1px solid black; background-color: blue; width: ; float: left; } 
     <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="parent" data-value="datavalue"> <div id="clickable"> Click me! </div> </div> 

    You are trying to use jQuery function data() on the DOM-object, which doesn't have such method.

    Use instead:

    var pNodeDataValue = event.target.parentNode.dataset.value;

    or

    var pNodeDataValue = $(event.target).parent().data('value');

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM