首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

使用jQuery将当前URL与UL中的herf匹配,如果匹配则添加类

名"link-active"。

jQuery是一个快速、简洁且易于使用的JavaScript框架,它已经成为Web开发领域中最受欢迎的工具之一。使用jQuery可以轻松地实现各种复杂的网页效果,提高开发效率。在这个问答中,我们将学习如何使用jQuery将当前URL与UL列表中的href匹配,并在匹配时添加类名"link-active"。

首先,我们需要引入jQuery库,并在页面中创建一个UL列表来存放链接。

代码语言:html
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery实现点击跳转</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <ul id="links">
        <li><a href="https://www.example1.com">Example 1</a></li>
        <li><a href="https://www.example2.com">Example 2</a></li>
        <li><a href="https://www.example3.com">Example 3</a></li>
    </ul>
    <script>
        $(document).ready(function () {
            $('#links a').on('click', function (e) {
                e.preventDefault();
                var url = $(this).attr('href');
                window.location = url;
            });
        });
    </script>
</body>
</html>

接下来,我们需要添加一个类名"link-active",以便在单击链接时添加样式。

代码语言:html
复制
<body>
    <ul id="links">
        <li><a href="https://www.example1.com" class="link-active">Example 1</a></li>
        <li><a href="https://www.example2.com">Example 2</a></li>
        <li><a href="https://www.example3.com">Example 3</a></li>
    </ul>
    <script>
        $(document).ready(function () {
            $('#links a').on('click', function (e) {
                e.preventDefault();
                var url = $(this).attr('href');
                window.location = url;
            });
        });
    </script>
</body>
</html>

现在,当用户单击链接时,链接将被添加到当前URL中,并添加类名"link-active"。这将使链接在单击时处于活动状态,并在页面上显示为选中状态。

代码语言:html
复制
<body>
    <ul id="links">
        <li><a href="https://www.example1.com" class="link-active">Example 1</a></li>
        <li><a href="https://www.example2.com">Example 2</a></li>
        <li><a href="https://www.example3.com">Example 3</a></li>
    </ul>
    <script>
        $(document).ready(function () {
            $('#links a').on('click', function (e) {
                e.preventDefault();
                var url = $(this).attr('href');
                window.location = url;
            });
        });
    </script>
</body>
</html>

现在,当用户单击链接时,链接将被添加到当前URL中,并添加类名"link-active"。这将使链接在单击时处于活动状态,并在页面上显示为选中状态。

代码语言:html
复制
<body>
    <ul id="links">
        <li><a href="https://www.example1.com" class="link-active">Example 1</a></li>
        <li><a href="https://www.example2.com">Example 2</a></li>
        <li><a href="https://www.example3.com">Example 3</a></li>
    </ul>
    <script>
        $(document).ready(function () {
            $('#links a').on('click', function (e) {
                e.preventDefault();
                var url = $(this).attr('href');
                window.location = url;
            });
        });
    </script>
</body>
</html>

现在,当用户单击链接时,链接将被添加到当前URL中,并添加类名"link-active"。这将使链接在单击时处于

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券