首页 > 解决方案 > Finding a class by dynamic id and accessing the data value

问题描述

I have tree structured data where I want to get the id's of each parent on clicking on particular parent. This is similar to my question here

I am unable to get the required alert can some one let me know what is wrong

$(".chapter").on("click", function() {
  let id = $(this).attr("href");
  list = $.map($(id).find(".sportlist"), function(item) {
    alert($(item).data("value"))
  })
});
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet" />
<div class="tree-ehex col-md-3" style="padding-left:0px;float: left; width:215px;overflow-x:scroll;height:261px;" id="treeOrderDiv">
  <ul style="padding-left: 0px;" id="leftsubMenus-Ul">
    <li class="parent_li">
      <span style="font-family: serif;font-size: small;" title="Collapse this branch"><i class="tree-ehex-title glyphicon glyphicon-minus-sign"></i></span>
      <a href="#Parent" class='chapter'> Parent</a>
      <ul id='#Parent'>
        <li style="display: list-item;" data-value='20'>
          <a href="#"><span style="text-transform: uppercase;color:black;font-size: smaller;font-family: sans-serif"> Child1 </span></a>
        </li>
        <li style="display: list-item;" data-value='22'>
          <a href="#"><span style="text-transform: uppercase;color:black;font-size: smaller;font-family: sans-serif"> Child2 </span></a>
        </li>
      </ul>
    </li>
    <li class="parent_li">
      <span style="font-family: serif;font-size: small;" title="Collapse this branch"><i class="tree-ehex-title glyphicon glyphicon-minus-sign"></i></span>
      <a href="#Parent1" class='chapter'> Parent1</a>
      <ul id="#Parent1">
        <li class='sportlist' style="display: list-item;" data-value='22'>
          <a href="#"><span style="text-transform: uppercase;color:black;font-size: smaller;font-family: sans-serif"> Child</span></a>
        </li>
        <li class='sportlist' style="display: list-item;" data-value='24'>
          <a href="#"><span style="text-transform: uppercase;color:black;font-size: smaller;font-family: sans-serif"> Child1 </span></a>
        </li>
      </ul>
    </li>
  </ul>
</div>

标签: jquery

解决方案


You have number of options:

  1. change id attrs of ul from <ul id="#Parent"> to <ul id="Parent"> and leave js as-is
  2. or leave html as-is, but change js:
$(".chapter").on("click", function() {
 let id = $(this).attr("href");
 let chapter = $(document.getElementById(id));
 list = $.map(chapter.find(".sportlist"), function(item) {
   alert($(item).data("value"))
 })
});

推荐阅读