获取滑动列表元素的 ID Jquery 移动

Getting id of a swiped list element Jquery Mobile

我似乎无法获取所刷列表项的 id!

在此处查看代码:https://www.w3schools.com/code/tryit.asp?filename=FD82HCGZJ2PE

<script>
$(document).on("pagecreate","#pageone",function(){
  $("li, ul").on("swipe",function(){
  alert(event.target.id);
   });                       
});
</script>
<div data-role="page" id="pageone">
  <div data-role="header">
<h1>The swipe Event</h1>
  </div>
  <ul data-role="listview" data-inset="true" data-theme="b" data-divider-theme="a" data-count-theme="a">
<li data-role="list-divider">Pick Ups <span class="ui-li-count">1</span></li>

<li id="B3">
  <a href'ride_details.php?TripID=15'>
    <h2 id="h2">Some Rider</h2>
    <p><strong>555 code lane Freedy, Texas 75035</strong></p>
    <p>Jon Doe</p>
  </a>
</li>  
<li id="B3"><a href'ride_details.php?TripID=15' id="2">
  <h2>Some Rider</h2>
  <p><strong>555 code lane Freedy, Texas 75035</strong></p>
  <p>Jon Doe</p>
  </a>
</li>   
  
  <div data-role="footer">
<h1>Footer Text</h1>
  </div>
</div> 

这是因为,大多数时候,event.target 不是 li,而是其子元素之一。

还有其他错误:

1- event 没有传递给处理函数。

这个:$(document).on("pagecreate","#pageone",function(){
应该是:$(document).on("pagecreate","#pageone",function(event){

2- 不能在多个元素上使用相同的 id

3- 缺少 </ul>

并且我为第一个 li 添加了一个排除项以触发此("Pick Ups" 行)。

所以在下面的代码片段中,如果你查看控制台,你会看到触发事件的 event.target.tagNameid处理它的父 li

li 上使用 $(this) 使您能够捕获由其子项之一触发的事件。

$(document).on("pagecreate","#pageone",function(){
  $("ul li").not(":first").on("swipe",function(event){
    console.log("event target element: "+event.target.tagName);
    console.log("li id: "+$(this).attr("id") );
  });                       
});
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>



<div data-role="page" id="pageone">
  <div data-role="header">
    <h1>The swipe Event</h1>
  </div>
  <ul data-role="listview" data-inset="true" data-theme="b" data-divider-theme="a" data-count-theme="a">
    <li data-role="list-divider">Pick Ups <span class="ui-li-count">1</span></li>

    <li id="firstRider"><a href'ride_details.php?TripID=15'>
      <h2 id="h2">First Rider</h2>
      <p><strong>555 code lane
        Freedy, Texas 75035</strong></p>
      <p>Jon Doe</p>
      </a>
    </li>  
    <li id="secondRider"><a href'ride_details.php?TripID=15' id="2">
      <h2>Second Rider</h2>
      <p><strong>555 code lane
        Freedy, Texas 75035</strong></p>
      <p>Jon Doe</p>
      </a>
    </li>   
  </ul>

  <div data-role="footer">
    <h1>Footer Text</h1>
  </div>
</div>