2017-03-01 48 views
0

我似乎无法获得swiped列表项的ID!获取滑动列表元素的ID Jquery Mobile

见代码在这里: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>

回答

1

这是因为,大部分的时间中,event.target不是li,但其子元素之一。

有其他错误:

1的event没有传递到处理函数。

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

2 - 你不能对多个元素使用相同的id

3-丢失了</ul>

而且我在第一个li上添加了一个排除项(“Pick Up”行)。

所以在下面的片段,如果你看一下控制台,你会看到它会触发事件并处理它的父liidevent.target.tagName

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>