Jquery:向偶数列表元素添加一个类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1171179/
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: Adding a class to even an odd List-Elements
提问by andrej
I have the following jquery-code:
我有以下 jquery 代码:
<script type="text/javascript">
$(document).ready(function() {
$ ('ul.image-list li:even').addClass ('even');
$ ('ul.image-list li:odd').addClass ('odd');
});
</script>
and the following html:
和以下html:
<ul class="image-list">
<li>first element</li>
<li>second element</li>
...
<li>last element</li>
</ul>
However the jquery does not seem to be applied, because the li-tags don't get the proper classes (even or odd). What am I doing wrong? thanks
然而 jquery 似乎没有被应用,因为 li 标签没有得到正确的类(偶数或奇数)。我究竟做错了什么?谢谢
回答by PetersenDidIt
This works just fine for me. Why do you think its not working in your code?
这对我来说很好用。为什么你认为它在你的代码中不起作用?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$ ('ul.image-list li:even').addClass('even');
$ ('ul.image-list li:odd').addClass('odd');
});
</script>
<style>
.even{
background: gray;
}
.odd{
color:red;
}
</style>
</head>
<body>
<ul class="image-list">
<li>first element</li>
<li>second element</li>
<li>third element</li>
<li>fourth element</li>
<li>fifth element</li>
<li>last element</li>
</ul>
</body>
</html>
回答by andrej
you can alternatively use: .filter(":odd").addClass("odd")
你也可以使用: .filter(":odd").addClass("odd")
回答by peirix
Try removing the space between addClass
and (
尝试之间移除空间addClass
和(
Same with $
and your selector
与$
您的选择器相同
Are you using Firebug, if you are, look at the HTML, and see if the class names are being applied or not. If they are, you simply forgot to link your stylesheet. If they're not, then there's something wrong with your javascript.
您是否在使用 Firebug,如果是,请查看 HTML,看看是否正在应用类名。如果是,您只是忘记链接您的样式表。如果不是,则说明您的 javascript 有问题。
回答by peirix
First of all, are you sure you inserted your style sheet into your page? I often forget this. Second, have you inserted the jquery js file into your page? I forget this very often. Third, do what peirix says and it should work. I don't see whats wrong with it.
首先,您确定将样式表插入到页面中吗?我经常忘记这一点。其次,您是否将 jquery js 文件插入到您的页面中?我经常忘记这一点。第三,按照peirix说的去做,它应该可以工作。我看不出有什么问题。
回答by Elzo Valugi
Is it possible that you create the li dynamically? In that case the call to add the class should not be on ready() but on a callback after the insertion of the li.
你有可能动态创建 li 吗?在这种情况下,添加类的调用不应该在 ready() 上,而是在插入 li 之后的回调上。