[英]add class to closest ul
I'm trying to add a class to the following < ul > for a h3-element which contains the string "Informationen". 我正在尝试为以下<ul>添加一个类,其中包含字符串“Informationen”的h3元素。
That's how the html-output looks like now: 这就是html输出现在的样子:
<h3>Informationen</h3>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit</li>
<li>Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes</li>
<li>Donec quam felis, ultricies nec, pellentesque eu</li>
</ul>
I want to achieve the code is like this: 我想实现的代码是这样的:
<h3>Informationen</h3>
<ul class"normal">
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit</li>
<li>Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes</li>
<li>Donec quam felis, ultricies nec, pellentesque eu</li>
</ul>
I have several h3-elements with different strings, so I'm grabbing the correct one with this script: 我有几个不同字符串的h3元素,所以我用这个脚本抓住了正确的元素:
$('h3').each(function() {
var $this = $(this);
var text = $this.html();
if (text == 'Informationen'){
alert(text);
};
});
Now the alert shows me the string "Informationen" when an Element with this text/string is found. 现在,当找到带有此文本/字符串的元素时,警报会显示字符串“Informationen”。
To now add a class to the closest/next ul I tried this: 现在添加一个类到最近/下一个ul我试过这个:
$('h3').each(function() {
var $this = $(this);
var text = $this.html();
if (text == 'Informationen'){
//alert(text);
$this.closest('ul').addClass('normal');
};
});
But this didn't work, like the following script didn't work too: 但这不起作用,如下面的脚本也不起作用:
$('h3').each(function() {
var $this = $(this);
var text = $this.html();
if (text == 'Informationen'){
//alert(text);
$(this).closest('ul').addClass('normal');
};
});
Here's a fiddle for this: http://jsfiddle.net/JNtw2/1/ 这是一个小提琴: http : //jsfiddle.net/JNtw2/1/
Can anyone point me to a solution for this? 谁能指点我这个解决方案?
closest()
gets the closest matching parent element, you're looking for next()
as the UL comes right after the H3 closest()
得到最接近的匹配父元素,你正在寻找next()
因为UL就在H3之后
$('h3').each(function() {
var $this = $(this);
var text = $this.html();
if (text == 'Informationen'){
$this.next('ul').addClass('normal');
};
});
您需要使用next()方法而不是nearest()方法。
May I suggest you this instead? 我可以建议你这样吗?
Note: This assumes Informationen will not be contained within a sentence in another h3. 注意:这假定Informationen不会包含在另一个h3的句子中。
$('h3:contains(Informationen)').next().addClass('normal');
Also note that you do not have to pass a sector to next
if you know that every h3
tag is followed by a ul
tag. 另请注意,如果您知道每个
h3
标记后跟一个ul
标记,则不必将扇区传递给next
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.