2014-03-01 55 views
3

我试图将类添加到以下< 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/

任何人都可以指出我的解决方案吗?

回答

6

closest()获得最匹配的父元素,你要找next()作为UL来的权利后,H3

$('h3').each(function() { 
    var $this = $(this); 
    var text = $this.html(); 
    if (text == 'Informationen'){ 

     $this.next('ul').addClass('normal'); 

    }; 
}); 

FIDDLE

+0

太棒了! thx快速回复! –

2

相反,你需要使用最接近()方法next()方法。

1

我可以建议你这个吗?

注意:假设信息不会包含在另一个h3的句子中。

$('h3:contains(Informationen)').next().addClass('normal'); 

还要注意的是,你不必一个部门传递到next如果你知道,每一个h3标签后跟ul标签。

+0

不错和短... thx! –