jQuery / Javascript方法获取当前页面的标题,将其与字符串匹配,将类分配给该特定元素

jQuery / Javascript method to get title of current page, match it to a stringa, assign class to that specific element

本文关键字:串匹配 字符串 分配 元素 字符 获取 方法 Javascript 当前页 jQuery 标题      更新时间:2023-09-26

好的,假设我有:

<title>Monkey</title>

然后是一些导航:

<ul id="navigation">
    <li>
        <a href=#">Monkey</a>
    </li>
</ul>

随着网站的加载,页面的标题被存储为变量,然后我希望字符串与 #navigation 中的任何内容匹配,在本例中为 Monkey。找到文本字符串后,它会分配一个类:

<ul id="navigation">
    <li class="current">
        <a href="#">Monkey</a>
    </li>
</ul>

有什么例子可以参考我吗?

试试这个:

$('#navigation a').filter(function() {
    return $(this).text() == document.title;
}).closest('li').addClass('current');