【问题标题】:How to change active class on li element in JQuery and redirect the user to the specified page when li elelment is clicked?如何在 JQuery 中更改 li 元素上的活动类并在单击 li 元素时将用户重定向到指定页面?
【发布时间】:2017-12-12 16:06:36
【问题描述】:

我的脚本标签中有以下内容。但是,每当我单击 test.php 或 test2.php li 链接时,我都不会被重定向到相应的页面。 但是,活动类从 index.php 文件更改为 test.php 或 test2.php 文件,具体取决于单击了哪个链接,但我没有被定向到该页面。我尝试了以下链接中的解决方案,但现在它们产生了我想要的结果,即将我重定向到单击的页面并将活动类更新为 li 元素。

How to change active class while click to another link in bootstrap use jquery?

Active link after click

每当我取消注释此行 e.preventDefault() 时,我都可以导航到已单击但活动类未更新为 li 元素单击,但是当该行被注释时,我无法导航到单击的页面,而是在单击的 li 元素上更新活动类。

<div class="menu">
    <ul class="list">
        <li class="header">MAIN NAVIGATION</li>
        <li class="active">
            <a href="index.php">
                <i class="material-icons">home</i>
                <span>Home</span>
            </a>
        </li>
        <li class="">
            <a href="test.php">
                <i class="material-icons">group</i>
                <span>Test</span>
            </a>
        </li>
        <li class="">
            <a href="test2.php">
                <i class="material-icons">people</i>
                <span>Test2</span>
            </a>
        </li>
    </ul>
 </div>

还有script 代码:

$(document).ready(function () {
    $('.menu .list a').click(function(e) {

        $('.menu li.active').removeClass('active');

        var $parent = $(this).parent();
        $parent.addClass('active');
        e.preventDefault();
    });
});

test.php的内容如下:

<body class="theme-red">
    <nav class="navbar">
        <?php include_once('navbar.html'); ?>
    </nav>
    <section>
        <aside id="leftsidebar" class="sidebar">
            <?php include_once('left-side-bar.html');?>
        </aside>
    </section>

    <section class="content">
        <div class="container-fluid">
            <div class="row clearfix">
                <table id="tbl-users" class="table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tfoot>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                    </tfoot>
                    <tbody>
                    <?php
                        $accounts = get_details();
                        foreach($accounts as $acc){
                    ?>
                        <tr>
                            <td><?php echo $acc['id']; ?></td>
                            <td><?php echo $acc['name']; ?></td>
                        </tr>
                    <?php
                        }
                    ?>
                    </tbody>
                </table>
            </div>
        </div>
    </section>
</body>

【问题讨论】:

  • 我认为您需要使用 PHP 应用活动类。如果您取消注释 e.preventDefault(); 并单击链接,页面将刷新并且您使用 jQuery 所做的任何前端更改都将被重置。
  • 如果可以的话,添加 test.php 或 test2.php 的代码以准确了解它是什么。
  • @Highdef test.php已经添加了代码

标签: javascript jquery html css


【解决方案1】:

为什么会出现问题?

问题出现了,当您在点击时使用e.preventDefault() 锚标签,the default behaviour is to redirect the page,就是这样 为什么页面没有加载但active class gets added。但当 你don't use e.preventDefault(),马上page redirects 和你did happen but before it was redirected 的改变而不是 对于新页面(可以重定向当前页面或其他页面),这就是您添加 can't see the class active 的原因 它。

.

如何解决问题?

嗯,有几种方法可以解决这个问题。我会说从 test.php 或 test2.php return a value,你可以 validate 反对 带有if-else conditions 的 javascript,如果值与您所做的匹配 那个 li 类是活跃的。

您需要进行以下更改:

在你有超链接的每个页面上添加一个 span

<span id="curpage" style="display:none;">test.php</span>

然后,在你的 body 标签末尾添加一个脚本(你可以在一个单独的文件中添加这个脚本,并使用&lt;?php include(".."); ?&gt; 包含在你的所有 php 文件中:

$('a[href=\"' + $("#curpage").text() + '\"]').parent().addClass("active");

这是一个示例代码,您可以尝试实施。制作2个文件 名为 a.html 的同一目录,代码如下:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
  <span id="curpage" style="display:none;">a.html</span>
  <div class="menu">
  <li><a href="b.html">1</a></li>
  <li><a href="a.html">2</a></li>
</div>
<script>
  $('a[href=\"' + $("#curpage").text() + '\"]').parent().css("color","red");
</script>
</body>
</html>

和 b.html 有代码:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
  <span id="curpage" style="display:none;">b.html</span>
  <div class="menu">
  <li><a href="b.html">1</a></li>
  <li><a href="a.html">2</a></li>
</div>
<script>
  $('a[href=\"' + $("#curpage").text() + '\"]').parent().css("color","red");
  </script>
  </body>
</html>

现在,当您通过单击链接更改页面时,您可以看到 子弹的颜色如何变化。

【讨论】:

  • 如果您能展示您的解决方案,您将赢得我的投票 :)
  • @UncaughtTypeError 如果我知道 OP 的 test.php 代码究竟包含什么,或者它是否重定向回或者是另一个带有导航栏的页面,我可以做到。如果它是另一个带有导航栏的页面,一个更简单的解决方案是让 li 在该页面上针对该特定选项处于活动状态。
  • 无论如何都要考虑编写一个快速的 jQuery 解决方案。它可能仍然对遇到相同或类似问题的其他人有所帮助。
  • test.php 不包含任何允许用户重定向回来的链接。导航到每个相应页面的链接位于一个组件中,例如 left-sideBar.html,它包含在 test.php 和 test2.php 文件中。
  • @AndreReid 是否可以添加 test.php 的代码,因为如果它不是脚本,那么解决方案可能比想象的更简单。
【解决方案2】:

我认为您不应该仅在单击 li 链接时更改“活动”类。认为当您将用户从另一个页面重定向到特定页面时,li 链接“OnClick”事件根本不会被触发,因此活动菜单链接将无法正确显示。 现在,我通常解决这个问题的方法(不知道它是否是最优雅的解决方案,但它有效)是在每个 html 内容模板的顶部放置一个标签(我假设你正在使用模板此处的页眉、页脚和内容),我给它一个描述性 ID,例如“页面名称”或“部分”,并为其添加一个数据属性,其中包含此页面“属于”的菜单链接的名称:

<div id="page-name" data-page="home-page">

然后使用 JQuery,您可以像这样询问 div 的数据:

var current_page = $("#page-name").data("page");

然后根据用户当前所在的页面更改菜单链接类:

// remove the "active" class from ALL the links first
$(".menu li a").removeClass("active");

if (current_page === "home-page") {
    // add the "active" class just to the link you want
    $("#home-page-link").addClass("active")
}

当然,您可以通过开关来执行此操作,并且您必须在所有页面上加载 js 文件(这就是使用 Header 模板如此重要的原因,因为您只需要包含一次)。另外,在 html 的“data-page”属性中,“page”部分可以是任何东西,只记得稍后适当地调用它。 希望我能帮上忙。

【讨论】:

  • 但我们不知道 test.php 和 test2.php 是由什么组成的,以及它们是否只是 HTML 页面,或者它们是否运行脚本并重定向回来。
  • test.php 和 test2.php 不包含任何标题或脚本标签来将用户重定向回上一页。
  • @Alex_89 为您提供解决方案,#home-page-link 是指向活动页面的实际链接。例如,#test.php
  • 不,在这种情况下,$("#home-page-link") 选择器引用了实际的菜单链接(即:菜单中的特定 li 标签或按钮)。例如,您要突出显示的那个。
【解决方案3】:

要在页面加载时向当前页面的导航项动态添加一个类,请考虑:

  1. 查看当前页面的url:
    $(location).attr('href')OR $(location).attr('pathname')
  2. 通过导航菜单的锚元素 (a) 循环到 确定是否有任何 href 属性值与当前的匹配 使用.indexOf() 方法进行条件检查的页面网址:
    if(anchorEl.indexOf(currentPageUrl) &gt;= 0)
  3. 如果有,请使用.addClass() 方法添加所需的类: $(this).addClass('current');

代码片段演示:

注意:仅供演示
下面嵌入的代码 sn-p 使用特定的 url 来提供工作示例演示预期的功能。相应调整以适用于给定的生产环境。

$(document).ready(function () {
    var currentPageUrl = $(location).attr('href'), // store current page url in variable
        anchorEl;
    
    $('.menu a').each(function(){
    
      anchorEl = $(this).attr('href'); // store href atribute of current anchor element in iteration
      console.log('anchor link url:',anchorEl);
      console.log('current url of window:',currentPageUrl);
    
      if(anchorEl.indexOf(currentPageUrl) >= 0) { // if anchor element contains 
        $(this).addClass('current');
        console.log('class "current" was added.');
      }
    });
});

/*

Note:
$(location).attr('href') = full absolute path (https://stacksnippets.net/js)
$(location).attr('pathname') = relative path (/js)

*/
.current {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
  <ul class="list">
    <li>
      <a href="https://stacksnippets.net/foobar1">
          <span>foobar #1</span>
      </a>
    </li>
    <li>
      <a href="https://stacksnippets.net/foobar2">
          <span>foobar #2</span>
      </a>
    </li>
    <li>
      <a href="https://stacksnippets.net/js">
          <span>This should be the <em>current</em> url</span>
      </a>
    </li>
  </ul>
</div>

【讨论】:

    【解决方案4】:

    您应该知道e.preventDefault() 将阻止调用它的对象的默认行为(在这种情况下重定向)。因此,您正在阻止您的应用程序重定向到您指定的 href

    你可以像这样改变你的功能代码:

    $(document).ready(function () {
        $('.menu .list a').click(function(e) {
    
            $('.menu li.active').removeClass('active');
    
            var $parent = $(this).parent();
            $parent.addClass('active');
            e.preventDefault();
    
            //Here is needed change
            location.href = $(this).attr('href');
        });
    });
    

    编辑 1: 所以你可以像这样工作:

    1) 为每个li标签指定一个类名

    2) 重定向和页面加载后发送必须有active类的类名

    3) 从url 读取传递的类名,并在li 标签中添加/删除

    所以你的html 代码如下:

    <div class="menu">
        <ul class="list">
            <li class="header">MAIN NAVIGATION</li>
            <li class="home active">
                <a href="index.php">
                    <i class="material-icons">home</i>
                    <span>Home</span>
                </a>
            </li>
            <li class="group">
                <a href="test.php">
                    <i class="material-icons">group</i>
                    <span>Test</span>
                </a>
            </li>
            <li class="people">
                <a href="test2.php">
                    <i class="material-icons">people</i>
                    <span>Test2</span>
                </a>
            </li>
        </ul>
     </div>
    

    如果你需要script根据我解释的这个解决方案编码,所以我会更新我的答案。

    编辑 2: 您的文件中需要有以下 script 代码:

    function setActiveClass() {
        //Remove active class from all li tags
        $('.menu li.active').removeClass('active');
        //Find current url
        var url = $(location).attr('href');
    
        if (url.contains("activeClass")) {
            //Find the index of active class in url
            var start = url.indexOf("#activeClass");
            //Add 6 unit to start index because of the longest class name is people which has 6 character
            var end = start + 6;
            //Fetch passed class name from url
            var className = url.substring(start, end);
    
            //Add active class corresponding to passed class name
            if(className.contains("home"))
                $(".home").addClass('active');
            else if(className.contains("group"))
                $(".group").addClass('active');
            else
                $(".people").addClass('active');
        } else {
            //Add active class for default mode (when we have not any redirect yet)
            $("#defaultLiTag").addClass('active');
        }
    }
    
    $(document).ready(function () {
        //Call the function
        setActiveClass();
    
        $('.menu .list a').click(function(e) {
            e.preventDefault();
    
            var classNameOfParent = $(this).parent().attr('class');
    
            var classNameToBePassedByUrl = "home";
    
            if(classNameOfParent.contains("group"))
                classNameToBePassedByUrl = "group";
            else if(classNameOfParent.contains("people"))
                classNameToBePassedByUrl = "people";
    
            location.href = $(this).attr('href') + "#activeClass=" + classNameToBePassedByUrl;
        });
    });
    
    【解决方案5】:

    经过大量搜索后,我遇到了同样的问题,我可以在此链接中找到此解决方案,希望对您有所帮助。虽然您应该删除活动类并将活动类添加到单击的导航栏项目,但您应该在新页面重新加载时使用 location.href 添加活动类。

    https://santosh-shah.com/add-class-active-page-refresh-jquery/

    【讨论】:

    • 请附上你自己的答案,然后总结。不要复制和粘贴一些参考资料,可以添加参考资料以获取更多详细信息,但不能作为答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    • 2020-05-18
    相关资源
    最近更新 更多