如何在不使用 class 或 id 的情况下 select 2nd h2? jquery
how to select 2nd h2 without using class or id? jquery
所以我有一个需要 class 的脚本,因为我将更改 class。
有什么方法可以 select .date class (h2) 而无需实际使用 class?
<div id="sortcontainer">
<li class="game" id="45">
<a class="gamelink" href="link">
<img class="image" src="games_category_placeholder.jpg">
<h2 class="title">Some game</h2>
<h2 class="date" id="2017">(2017)</h2>
<h3 class="thumbrating">45/100</h3>
</a>
</li>
</div>
这是我所拥有的,但它无法与第 n 个 selector 一起使用。
当我替换为 .date 时它起作用了。
$('#datereleased').on('click', function(){
var $sortContainer = $('#sortcontainer');
$sortContainer.append(
$sortContainer.children().sort(function(a, b){
return (
parseInt($("h2:nth-child(2)", b).attr('id'), 10)
-
parseInt($("h2:nth-child(2)", a).attr('id'), 10)
);
}).get()
);
});
有什么想法吗?
您可以使用 :nth-of-type
css 选择器。
console.log(
document.querySelector('#sortcontainer .gamelink h2:nth-of-type(2)')
);
<div id="sortcontainer">
<li class="game" id="45">
<a class="gamelink" href="link">
<img class="image" src="games_category_placeholder.jpg">
<h2 class="title">Some game</h2>
<h2 class="date" id="2017">(2017)</h2>
<h3 class="thumbrating">45/100</h3>
</a>
</li>
</div>
jQuery 有 .eq()
方法,用于根据元素在集合中的索引过滤当前集合的元素。
$(a).find('h2').eq(1).attr('id') //note that the first element is 0
此外,元素集合可以由 jQuery 对象的零索引数组引用:
$(a).find('h2')[1].id
在这种情况下,使用的是 DOM 元素而不是 jQuery 对象。
.eq()
的文档:http://api.jquery.com/eq/
所以我有一个需要 class 的脚本,因为我将更改 class。
有什么方法可以 select .date class (h2) 而无需实际使用 class?
<div id="sortcontainer">
<li class="game" id="45">
<a class="gamelink" href="link">
<img class="image" src="games_category_placeholder.jpg">
<h2 class="title">Some game</h2>
<h2 class="date" id="2017">(2017)</h2>
<h3 class="thumbrating">45/100</h3>
</a>
</li>
</div>
这是我所拥有的,但它无法与第 n 个 selector 一起使用。 当我替换为 .date 时它起作用了。
$('#datereleased').on('click', function(){
var $sortContainer = $('#sortcontainer');
$sortContainer.append(
$sortContainer.children().sort(function(a, b){
return (
parseInt($("h2:nth-child(2)", b).attr('id'), 10)
-
parseInt($("h2:nth-child(2)", a).attr('id'), 10)
);
}).get()
);
});
有什么想法吗?
您可以使用 :nth-of-type
css 选择器。
console.log(
document.querySelector('#sortcontainer .gamelink h2:nth-of-type(2)')
);
<div id="sortcontainer">
<li class="game" id="45">
<a class="gamelink" href="link">
<img class="image" src="games_category_placeholder.jpg">
<h2 class="title">Some game</h2>
<h2 class="date" id="2017">(2017)</h2>
<h3 class="thumbrating">45/100</h3>
</a>
</li>
</div>
jQuery 有 .eq()
方法,用于根据元素在集合中的索引过滤当前集合的元素。
$(a).find('h2').eq(1).attr('id') //note that the first element is 0
此外,元素集合可以由 jQuery 对象的零索引数组引用:
$(a).find('h2')[1].id
在这种情况下,使用的是 DOM 元素而不是 jQuery 对象。
.eq()
的文档:http://api.jquery.com/eq/