使用DOM遍历获取attr值失败

时间:2015-11-27 09:49:13

标签: javascript jquery

<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。我的代码出了什么问题?

1 个答案:

答案 0 :(得分:2)

您需要获取具有该属性的span,以便将选择器更改为span[data-tocityid]span[data-fromcityid]。如果只有一个元素,则不需要:last:first

&#13;
&#13;
$(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;
&#13;
&#13;

您的代码中的错误是您错误地添加了:first:last,您只需要交换它们

&#13;
&#13;
$(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;
&#13;
&#13;

仅供参考:您还可以使用data()方法获取data-*属性值。