我可以轻松使用索引值吗?我认为使用自然索引值比使用类更好。我想以这种方式使用.index。
HTML
<div id="test">
<ul>
<li>Im index 0</li>
<li>Im index 1</li>
<li>Im index 2</li>
<li>Im index 3</li>
</ul>
</div>
Pseudo(Jquery)Javascript
$('#test ul > li').index(2).hide();
$('#test ul > li').index(1).click(function() {
alert('lulz you clicked the li with the index value of 1 bro');
});
我找不到如何使用.index值以这种方式工作的线索..是否可以使用此方法轻松工作?
答案 0 :(得分:12)
您可以使用eq
:
$('#test ul > li').eq(2).hide();
它也可以是选择器的一部分:
$('#test ul > li:eq(2)').hide();
如果您想要li
中所有ul
中的第三个#test
,您可以使用nth-child
(请注意,它是从1开始的):
$('#test ul > li:nth-child(3)').hide();
答案 1 :(得分:5)
是的,你可以。但是,您需要.eq()
,而不是.index()
:
$('#test ul > li').eq(2).hide();
或作为选择器的一部分:
$('#test ul > li:eq(2)').hide();
答案 2 :(得分:1)
您正在使用整数(数字),但只能将它与选择器或元素一起使用。 here
编辑:
你可以编写自己的函数:
function indexValue(index)
{
$(element).each(function(key, val) {
if(key+1 == index) // + 1 because you started from 0
{
return val;
}
});
}
答案 3 :(得分:0)
$(document).ready(function(){
$("button#1").click(function(){
$("p").hide();
});
});
$(document).ready(function(){
$("button#2").click(function(){
$("p").show();
});
});
<button id="1">Clica-me</button>
<button id="2">Volta-me</button>