0

我需要获取 h1 PHP echoed Page Title 元素的值,然后使用它来查找 li PHP echoed category name 中的任何匹配项,然后如果匹配,则将一个类添加到 span。这在jquery中可能吗?

<h1>PHP echoed Page Title</h1>
<ul>
<li><a href="">PHP echoed category name</a>
<span class="open">X</span>
  <ul>
    <li><a href="">PHP echoed category name</a></li>
    <li><a href="">PHP echoed category name</a></li>
    <li><a href="">PHP echoed category name</a></li>
</ul>
</li>
</ul>
4

1 回答 1

3

这个解决方案中有一些假设。

假设 1:h1 是页面上唯一的 h1。

假设 2:您要附加的类是 'fooClass'

假设 3:您不想删除任何其他类。

假设 4:您不想在 li 中测试严格的字符串相等性,您想查看文本是否存在,您关心大小写,并且通常不想做任何正则表达式/字符串按摩魔术。

    header_text = $('h1').text();
    $('.open ul li').each(function(){
        if($(this).text().indexOf(header_text) != -1){
             $(this).parent().parent().addClass('fooClass');
             return(true); //this will terminate execution to avoid adding fooClass more then once.
        }           
    });
于 2012-12-21T00:31:11.923 回答