<ul class="locations" style="height: 129px; overflow-y: auto; overflow-x: hidden;">
<li class="selected">
<span data-tocityid="1">kuala lumpur</span>
<span class="to_arrow">
<img src="images/pos/arrow.png">
</span>
<span data-fromcityid="2">singapore</span>
</li>
</ul>
我的jquery
$(document).on('click','#destination .locations li', function(){
var fromCityId = $(this).find('span:first').attr('data-fromCityId');
var toCityId = $(this).find('span:last').attr('data-toCityId');
});
我得到了undefined
。我的代码出了什么问题?
答案 0 :(得分:2)
您需要获取具有该属性的span
,以便将选择器更改为span[data-tocityid]
和span[data-fromcityid]
。如果只有一个元素,则不需要:last
或:first
$(document).on('click', '#destination .locations li', function() {
var fromCityId = $(this).find('span[data-fromcityid]').attr('data-fromcityid');
var toCityId = $(this).find('span[data-tocityid]').attr('data-tocityid');
console.log(toCityId, fromCityId);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="destination">
<ul class="locations" style="height: 129px; overflow-y: auto; overflow-x: hidden;">
<li class="selected">
<span data-tocityid="1">kuala lumpur</span>
<span class="to_arrow">
<img src="images/pos/arrow.png">
</span>
<span data-fromcityid="2">singapore</span>
</li>
</ul>
</div>
&#13;
您的代码中的错误是您错误地添加了:first
和:last
,您只需要交换它们
$(document).on('click', '#destination .locations li', function() {
var fromCityId = $(this).find('span:last').attr('data-fromCityId');
var toCityId = $(this).find('span:first').attr('data-toCityId');
console.log(toCityId, fromCityId);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="destination">
<ul class="locations" style="height: 129px; overflow-y: auto; overflow-x: hidden;">
<li class="selected">
<span data-tocityid="1">kuala lumpur</span>
<span class="to_arrow">
<img src="images/pos/arrow.png">
</span>
<span data-fromcityid="2">singapore</span>
</li>
</ul>
</div>
&#13;
仅供参考:您还可以使用data()
方法获取data-*
属性值。