将类添加到最接近的 UL



我正在尝试为包含字符串"Informationen"的 h3 元素在以下

    中添加一个类。

    这就是 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/

    谁能指出我的解决方案?

closest()获得最匹配的父元素,您正在寻找next(),因为 UL 紧随 H3 之后

$('h3').each(function() {
    var $this = $(this);
    var text = $this.html();
    if (text == 'Informationen'){
        $this.next('ul').addClass('normal');
    };
});

小提琴

代替 closest() 方法,您需要使用 next() 方法。

我可以建议你这个吗?

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

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

另请注意,如果您知道每个h3标记后跟一个ul标记,则不必将扇区传递给next

最新更新