2013-03-12 33 views
0

我有一個腳本工作,根據url切換樣式表。允許通配符在url結尾的JavaScript條件css風格

它必須這樣做,因爲該網站使用smarty模板,我不想改變核心文件或核心css。

現在我必須添加每個單獨頁面的URL路徑名。有更多的頁面,這是不切實際的。

因此,例如,而不是/ojs/index.php/index/user/register/ojs/index.php/index/user/profile我想打電話給/ojs/index.php/index/user/*所以當時所有頁面/user/下將應用了樣式表。

這樣做的最好方法是什麼?我看過一些類似的帖子,但並不完全是我需要的。

var loc = window.location; 
var currentURL = loc.pathname; 

if (currentURL=='/ojs/index.php/index' || currentURL=='/ojs/' || currentURL=='/ojs/index.php/index/about' || currentURL=='/ojs/index.php/index/user/register' || currentURL=='/ojs/index.php/index/user/profile' || currentURL=='/ojs/index.php/index/admin/' || currentURL=='/ojs/index.php/index/admin/auth') 

loadjscssfile("/ojs/plugins/themes/main-theme/main-theme.css", "css") 

回答

0

您可以使用Regular Expression

// unless you were using loc for something else, there is no need to store it, 
// just chain to get the pathname 
var currentURL = window.location.pathname, 
    // create a regular expression that will match all pages under user 
    usersPattern = new RegExp('^/ojs/index\.php/index/user/.*'); 

if (usersPattern.test(currentURL)) { 
    loadjscssfile("/ojs/plugins/themes/main-theme/main-theme.css", "css") 
} 

與正則表達式一樣,你需要小心你正在做的事情,以使其正確。下面是這種表達是如何工作的一個簡短的解釋:

  • ^告知用戶,如果字符串/ojs/開始它只匹配等
  • 中間的\.逃脫.,告訴它在index.php.是字面點
  • .在端部將匹配任何字符
  • *.將匹配前一字符的0或多個實例(一ny字符在這種情況下)

我用RegExp構造函數創建了這個正則表達式,但它也可以用正則表達式來完成。一般來說,使用文字是一個更好的主意,但在這種情況下,我使用了構造函數,因爲它將一個字符串作爲參數,所以我不必在模式中轉義/字符。如果我們用文字來做到這一點,而不是這樣的:

usersPattern = new RegExp('^/ojs/index\.php/index/user/.*'); 

它應該是這樣的:

usersPattern = /^\/ojs\/index\.php\/index\/user\/.*/; 

不需要逃離那些/使得它多一點可讀性。

+0

對不起,謝謝你。這工作。非常感謝。將會標記以便其他人可以使用正則表達式找到如何執行此操作或類似操作。 – rootl 2013-07-22 18:44:48

+0

如果我的答案解決了您的問題,那麼我們將不勝感激;-) – 2013-07-23 00:17:46