[英]Add class dynamically using jquery
I am trying to add the class last dynamically to every second row with jQuery as below 我正在尝试使用jQuery将动态最后一个类添加到第二行,如下所示
<div class= "news-row">
<article class="news-container fixed-page"> blah blah</article>
<article class="news-container fixed-page"> blah blah2</article>
</div>
Below is the jquery 下面是jQuery
<script type="text/javascript">
$(document).ready(function () {
$('article.news-container :nth-child(2n)').addClass('last');
});
</script>
This does not add the class. 这不会添加类。 Any help will be appreciated. 任何帮助将不胜感激。 I want the every second article element to have "last" appended. 我希望第二个文章元素都附加“最后一个”。
An article
node isn't a child of itself, so that selector won't work. article
节点本身不是子节点,因此选择器将不起作用。 Start with the parent instead (whose children are the <article>
nodes): 而是从父项开始(其子项是<article>
节点):
$('.news-row :nth-child(2n)').addClass('last');
You are forgetting a double quote on the first line, also do not add space before selector (:nth-child) 您忘记了第一行的双引号,也不要在选择器(:nth-child)之前添加空格
CodePen link below 下面的CodePen链接
http://codepen.io/kkirsche/pen/Hkutd http://codepen.io/kkirsche/pen/Hkutd
HTML: HTML:
<div class="news-row">
<article class="news-container fixed-page"> blah blah</article>
<article class="news-container fixed-page"> blah blah2</article>
</div>
CSS: CSS:
.last {
color: red;
}
JS: JS:
$('article.news-container:nth-child(2n)').addClass('last');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.