簡體   English   中英

jQuery,基於data屬性設置活動類

[英]jQuery, setting an active class based on the data attribute

經過廣泛的研究,我沒有想到任何能完美發揮作用的東西。

我的HTML

<div class="option" data-toggle="tooltip" data-placement="right" data-name="Home" data-url="/" title="Home">
    <p class="select-button"><i class="fa fa-home" aria-hidden="true"></i></p>
</div>

我的JS

$(function(){
    activeClass();
});

function activeClass(){
    //define the page url
    var path = window.location.pathname;
    path = path.replace(/\/$/, "");
    //decode the uri
    path = decodeURIComponent(path);

    //find each item containing .option as a class
    $(".option").each(function() {
        //store the data of these in a variable
        var ref = $(this).data("url"); 
        if(path.substring(0,ref.length) == ref){
            //set the closest one to active
            $(this).addClass('active');
        }
    })  
}

JS確實可以工作,但是當URL上帶有/的頁面上但主頁上沒有主頁按鈕時,它也使主頁按鈕具有活動類。

其目的是使網頁檢測或確定與頁面URL匹配的按鈕。 例如,主頁將與我提供的按鈕代碼匹配,或者/ auth / login將與登錄按鈕匹配。

最后,歸結為字符串比較。 如果根據字符串的開頭對它們進行比較,則如果兩條或多條路徑以相同的字符序列開頭,但一條路徑比另一條短,則可能會遇到麻煩。 這是非常常見的情況,“ /”是主URL,也是所有其他URL的第一個字符。

如果您不希望在.option這樣的“沖突” URL(“ /”除外),則可以使用主URL創建一個簡單的異常,如下面的示例所示。

$(function () {
    // Immediate function
    !function () {
        var path = window.location.pathname;
        // Changed regex to not replace single "/"
        path = path.replace(/.+\/$/, "");
        path = decodeURIComponent(path);

        // Exception if path is "/"
        if (path === '/') {
            $('[data-url="/"]').addClass('active');
            return;
        }

        // Check all `.options` but not `[data-url="/"]`
        $('[data-url]:not([data-url="/"])').each(function() {
            var ref = $(this).data('url');

            if (path.indexOf(ref) === 0) {
                $(this).addClass('active');
            }
        })  
    }()
});

暫無
暫無

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

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