单击li时,如何获取li内深的span的ID

时间:2019-06-01 18:38:39

标签: jquery

 <li class="service">
                    <div class="name">>
                       <span class="price"></span>
                       Stock<span class="stock" id="ds"></span>
                    </div>
</li>
 <li class="service">
                    <div class="name">>
                       <span class="price"></span>
                       Stock<span class="stock" id="ju"></span>
                    </div>
</li>
 <li class="service">
                    <div class="name">>
                       <span class="price"></span>
                       Stock<span class="stock" id="zx"></span>
                    </div>
</li>

我想获取具有单击的li的类名称为stock的跨度的ID

$("li").click(function() {

        });

3 个答案:

答案 0 :(得分:1)

您必须使用li添加类选择器,这样它就不会在所有lis上添加。

尝试一下:

$("li.service").click(function() {
      var spanid = $(this).find('span.stock').attr('id');

      alert(spanid);
});

答案 1 :(得分:0)

您可以在this事件处理程序中使用click关键字来引用被单击的li。从那里,您可以使用find()来检索您需要的span,然后再调用prop()来获取ID。试试这个:

$("li").click(function() {
  var id = $(this).find('.stock').prop('id');
  console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="service">
    <div class="name">>
      <span class="price"></span> 
      Stock <span class="stock" id="ds"></span>
    </div>
  </li>
  <li class="service">
    <div class="name">>
      <span class="price"></span> 
      Stock <span class="stock" id="ju"></span>
    </div>
  </li>
  <li class="service">
    <div class="name">>
      <span class="price"></span>
      Stock <span class="stock" id="zx"></span>
    </div>
  </li>
</ul>

答案 2 :(得分:0)

您可以使用find来获得股票类别的跨度。使用attr获取属性。

$("li").click(function() {
  var id = $(this).find('.stock').attr('id');
  console.log(id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="service">
    <div class="name">
      <span class="price"></span> Stock
      <span class="stock" id="ds"></span>
    </div>
  </li>
  <li class="service">
    <div class="name">
      <span class="price"></span> Stock
      <span class="stock" id="ju"></span>
    </div>
  </li>
  <li class="service">
    <div class="name">
      <span class="price"></span> Stock
      <span class="stock" id="zx"></span>
    </div>
  </li>
</ul>