使用 jquery 将类添加到第 n 个孩子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16241971/
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
add class to nth-child with jquery
提问by T0w3ntuM
I'm trying to add a class using jquery to the nth-child so that it'll work in IE. It doesn't seem to be working, I have followed a few examples with no results. I have linked the fiddle
我正在尝试使用 jquery 添加一个类到第 n 个子节点,以便它可以在 IE 中工作。它似乎不起作用,我遵循了一些没有结果的例子。我已经链接了小提琴
http://jsfiddle.net/aosto/XghbU/
http://jsfiddle.net/aosto/XghbU/
<div id='tasklist'>
<ul class='header'>
<li>
<div class='listitem head'>Number</div>
<div class='listitem head'>Description</div>
<div class='listitem head'>Start Date</div>
<div class='listitem head'>Due Date</div>
<div class='listitem head'>Edit/View</div>
<div class='listitem head'>Complete</div>
</li>
</ul>
</div
#tasklist ul {
clear:both;
list-style:none;
margin:0;
padding:0;
}
#tasklist ul li {
clear:both;
margin:3px;
padding:3px;
}
.listitem {
float:left;
display:inline-block;
}
.listitem2 {
width:400px;
}
$( document ).ready(function() {
$('#tasklist ul li:nth-child(2)').addClass("listitem2");
});
<head>
<link href='css/style.php' type='text/css' rel='stylesheet'>
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="css/ie_style.css" />
<![endif]-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$('.listitem:nth-child(2)').addClass("listitem2");
});
</script>
</head>
回答by Fico
Your selector should be the following in order to address your second div inside the list tag!!
您的选择器应该如下所示,以便在列表标签内处理您的第二个 div!!
$('#tasklist ul li div:nth-child(2)')
Or any case you should have at list two list elements in your markup if you are actually trying to target a list element.
或者在任何情况下,如果您实际上试图定位一个列表元素,那么您应该在标记中列出两个列表元素。
回答by Nitin Kanish
jQuery(".menu-item").click(function(){
jQuery(this).find('ul.sub-menu').toggleClass("display_both");
});