我试图将类添加到以下< ul>中,其中包含字符串“Informationen”的h3元素。将类添加到最接近的ul
这就是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>
我要实现的代码是这样的:
<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>
我有几个H3元素具有不同的字符串,所以我用这个脚本抓取正确的一个:
$('h3').each(function() {
var $this = $(this);
var text = $this.html();
if (text == 'Informationen'){
alert(text);
};
});
现在警报显示我字符串“Informationen”当找到包含此文本/字符串的元素时。
到现在类添加到最近的一个/下UL我尝试这样做:
$('h3').each(function() {
var $this = $(this);
var text = $this.html();
if (text == 'Informationen'){
//alert(text);
$this.closest('ul').addClass('normal');
};
});
但这并没有工作,像下面的脚本没有工作过:
$('h3').each(function() {
var $this = $(this);
var text = $this.html();
if (text == 'Informationen'){
//alert(text);
$(this).closest('ul').addClass('normal');
};
});
这里有一个小提琴:http://jsfiddle.net/JNtw2/1/
任何人都可以指出我的解决方案吗?
太棒了! thx快速回复! –