javascript JQuery - $('#test ul > li').index(2).hide(); - 可能的?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4591754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery - $('#test ul > li').index(2).hide(); - possible?
提问by Tomkay
Can I work with the index value so easily? I think using the natural index values is better then using classes. I want to use the .index in that way.
我可以如此轻松地使用索引值吗?我认为使用自然索引值比使用类更好。我想以这种方式使用 .index 。
Html
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
伪(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');
});
I doesnt find a clue how to work this way with the .index value.. is it possible to work that easily with this method??
我不知道如何使用 .index 值以这种方式工作.. 使用这种方法可以轻松工作吗?
回答by Kobi
You can use eq:
您可以使用eq:
$('#test ul > li').eq(2).hide();
It can also be a part of your selector:
它也可以是选择器的一部分:
$('#test ul > li:eq(2)').hide();
If you want the third liin all uls in #test, you can use nth-child(note it is 1-based):
如果您想要li所有uls 中的第三个#test,您可以使用nth-child(注意它是基于 1 的):
$('#test ul > li:nth-child(3)').hide();
回答by David Tang
Yes you can. You want .eq()however, instead of .index():
是的你可以。.eq()然而,你想要,而不是.index():
$('#test ul > li').eq(2).hide();
Or as part of the selector:
或者作为选择器的一部分:
$('#test ul > li:eq(2)').hide();
回答by Yoram de Langen
You're using it with an integer (number), but you can only use it with a selector or element. here
您将它与整数(数字)一起使用,但您只能将它与选择器或元素一起使用。这里
Edit:
You could write your own function like this:
编辑:
您可以像这样编写自己的函数:
function indexValue(index)
{
$(element).each(function(key, val) {
if(key+1 == index) // + 1 because you started from 0
{
return val;
}
});
}
回答by Alexssandrolima
$(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>

