2016-09-01 22 views
0

下面的jQuery功能正常工作,並根據URL向/signin/頁面上的<body>HTML元素添加full類。如何使用jQuery將主體類添加到首頁和內部頁面?

// add full class to sign in page body based on url 

$(function() { 
    var loc = window.location.href; // returns the full URL 
    if(/signin/.test(loc)) { 
    $('body').addClass('full'); 
    } 
}); 

我要完成相同功能,內前/主頁,或/ URL上完全一樣的事情。我該怎麼做呢?

+0

您能否提供一些進一步的說明 - 您還試圖附加附加課程的元素是什麼? – aphextwix

+0

@aphextwix我想爲'' HTML元素添加一個'full'類。 – Liz

+0

看到我的答案。我相信你正在尋找。 – Vasif

回答

1

正則表達式很慢。更快的方法:

function() { 
    var loc = window.location.pathname; // returns the pathname 
    if(loc == '' || loc == '/') { 
     $('body').addClass('full'); 
    } 
}); 
+0

這工作 - 似乎也稍微快一點。 – Liz

+0

@LizBanach很高興能爲您服務! –

0

使用適當的正則表達式。 /^\/$/你的情況。

/^\/$/.test('/') // true 
/^\/$/.test('/asdf') //false 

在您的情況下進一步添加到它。我會用window.location.pathname

$(function() { 
    var loc = window.location.pathname; // returns the pathname 
    if(/^\/$/.test(loc)) { 
     $('body').addClass('full'); 
    } 
}); 
+0

這對我有用。我最後的代碼是: '//加滿級在頁面主體簽收BG圖像 $(函數(){VAR LOC = window.location.pathname; //返回路徑 如果(/登入/ ('body')。addClass('full'); } if(/^\/$ /。test(loc)){(body)addClass 'full'); } }); ' – Liz

相關問題