簡體   English   中英

當單擊lielment時,如何更改jQuery中li元素上的活動類並將用戶重定向到指定頁面?

[英]How to change active class on li element in JQuery and redirect the user to the specified page when li elelment is clicked?

我的腳本標簽中包含以下內容。 但是,每當我單擊test.php或test2.php li鏈接時,都不會重定向到相應頁面。 但是,活動類從index.php文件更改為test.php或test2.php文件,具體取決於單擊了哪個鏈接,但我沒有直接轉到該頁面。 我嘗試了以下鏈接中的解決方案,但現在它們產生了我想要的期望結果,即將我重定向到所單擊的頁面,並將活動類更新為li元素。

在使用Bootstrap的另一個鏈接中單擊時如何更改活動類?

點擊后激活鏈接

每當我取消注釋該行e.preventDefault()時,我都能夠導航到已單擊的鏈接,但活動類未更新為單擊的符號,但是當評論該行時,我無法導航到單擊的頁面,而是在單擊的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>

為什么會出現問題?

出現的問題是,當您在點擊錨標記時使用e.preventDefault()時, the default behaviour is to redirect the page ,這就是為什么頁面不加載但active class gets addedactive class gets added的原因。 但是,當您don't use e.preventDefault()page redirects立即page redirects ,並且您did happen but before it was redirected在更改did happen but before it was redirected了更改, did happen but before it was redirected而不是針對新頁面(可以將其重定向到當前頁面或其他頁面),這就是您的原因can't see the class active添加can't see the class active

如何解決問題?

好吧,有兩種方法可以解決這個問題。 我要說的是,從test.php或test2.php return a value ,如果該值與您匹配,則可以使用if-else conditions針對javascript進行validate ,從而使該li類成為活動類。

這是您需要進行的更改:

在您已超鏈接的每個頁面上添加一個跨度,即test.php,test2.php等, having text the same as your hyperlink錨標記中的having text the same as your hyperlink因此對於test.php,將跨度添加為:

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

然后,在body標簽的末尾添加一個腳本(您可以使用<?php include(".."); ?>將該腳本添加到單獨的文件中,並包含在所有php文件中:

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

這是一個示例代碼,您可以嘗試實現。 在名為a.html的同一目錄中制作2個文件,其代碼為:

 <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> 

現在,當您通過單擊鏈接更改頁面時,可以看到項目符號的顏色如何變化。

您應該知道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;
    });
});

我不認為僅在單擊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”部分可以是任何東西,只記得稍后適當地調用它即可。 希望我能幫上忙。

要在頁面加載時將類動態添加到當前頁面的導航項中,請考慮:

  1. 檢查當前頁面的URL:
    $(location).attr('href') $(location).attr('pathname')
  2. 使用.indexOf()方法進行條件檢查,循環瀏覽導航菜單的錨元素( a ),以確定是否有任何href屬性值與當前頁面url匹配:
    if(anchorEl.indexOf(currentPageUrl) >= 0)
  3. 如果有,請使用.addClass()方法添加所需的類: $(this).addClass('current');

代碼段演示:

注意:用於演示目的
下面嵌入的代碼段使用特定的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> 

經過大量搜索后,我遇到了同樣的問題,我可以在此鏈接中找到此解決方案,希望對您有所幫助。 盡管您應該刪除活動類並將活動類添加到單擊的導航欄項目,但是當重新加載新頁面時,應該使用location.href添加活動類。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM