我试图创建一个脚本,允许我检查具体位置的类,例如:
<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>
答案 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()
:
$(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;
或:Template literals
更清洁:
$(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;
答案 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>