使用JQuery从具有特定位置的li获取类

时间:2018-05-30 22:50:59

标签: javascript jquery

我试图创建一个脚本,允许我检查具体位置的类,例如:

<ul id='check_passengers'>
    <li>user one</li>
    <li>user two</li>
    <liclass='user-checked'>user three</li>
    <li>user four</li>
    <li>user five</li>
<ul>


<script>
$(document).ready(function() {
var position_to_search = 2;
var class_of_ul = $('#check_passengers li:' + position_to_search).attr('class');
console.log('User on position 3 : ' + class_of_ul);
});
</script>

3 个答案:

答案 0 :(得分:1)

使用css选择器:

像这样使用:

$(document).ready(function() {
  var position_to_search = 3;
  var class_of_ul = $('#check_passengers li:nth-child('+ position_to_search +'n)').attr('class');
  console.log('User on position 3 : ' + class_of_ul);
});

答案 1 :(得分:1)

使用jQuery&#39; s eq()

尝试以下操作

&#13;
&#13;
$(document).ready(function() {
  var position_to_search = 2;
  var class_of_ul = $('#check_passengers li:eq(' + position_to_search+')').attr('class');
  console.log('User on position 3 : ' + class_of_ul);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id='check_passengers'>
  <li>user one</li>
  <li>user two</li>
  <li class='user-checked'>user three</li>
  <li>user four</li>
  <li>user five</li>
<ul>
&#13;
&#13;
&#13;

或:Template literals更清洁:

&#13;
&#13;
$(document).ready(function() {
  var position_to_search = 2;
  var class_of_ul = $(`#check_passengers li:eq(${ position_to_search})`).attr('class');
  console.log('User on position 3 : ' + class_of_ul);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id='check_passengers'>
  <li>user one</li>
  <li>user two</li>
  <li class='user-checked'>user three</li>
  <li>user four</li>
  <li>user five</li>
<ul>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

使用css :nth-child(position)选择器。请注意,indexing从索引1

开始

如下所示

<ul id='check_passengers'>
    <li>user one</li>
    <li>user two</li>
    <liclass='user-checked'>user three</li>
    <li>user four</li>
    <li>user five</li>
<ul>


<script>
   $(document).ready(function() {
       var position_to_search = 2;
       var class_of_ul = $('#check_passengers li:nth-child(' + position_to_search + ')')
   .attr('class');
       console.log('User on position 2 : ' + class_of_ul);
   });
</script>