解決:a標籤點擊跳轉頁面後,爲被點擊的a標籤添加樣式的問題

  大家肯定遇到了過這個問題,當你點擊a標籤的時候,想要給a標籤,加上高亮選中的樣式,可是頁面刷新無法保存樣式,那怎麼辦呢?我提供一種方法:循環a的鏈接,然後與location.href去比對,如果相同,或包含有同樣字符串序列,則添加。
代碼如下:

    var url = window.location.href;
    $("a").each(function () {
        if (returnUrl($(this).attr("href")) == returnUrl(url)) {
            console.log($(this));
            $(this).addClass("selected");
        }
    });
    //以下爲截取url的方法
    function returnUrl(href) {
        var number = href.lastIndexOf("/");
        return href.substring(number + 1);
    }

  不一定非得用lastIndexOf()方法,還可以用substring()、substr()

  1. lastIndexOf() 方法可返回一個指定的字符串值最後出現的位置,在一個字符串中的指定位置從後向前搜索。
  2. substring() 方法用於提取字符串中介於兩個指定下標之間的字符。
  3. substr() 方法可在字符串中抽取從 start 下標開始的指定數目的字符

  或者直接:

 $("a").each(function () {
        var a_href = window.location.pathname;
        if ($(this).attr("href") == a_href) {
            console.log(123);
            $(this).addClass("selected");
        }
    });

  因爲我的a標籤是這樣的:

  <a th:href="@{'/user/news/'+${newsList.pageNum}+'/2/0'}"></a>

  遍歷出來等同於:

<a th:href=/user/news/0/1/0}"></a>

  所以我用的是 window.location.pathname這個屬性。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章