2010-08-28 23 views
1

我只想將下面的jQuery添加到以下頁面。如果URL有某個單詞,如何添加JavaScript?

http://www.mywebsite.com/check-8.asp 

http://www.mywebsite.com/edit-8.asp 

http://www.mywebsite.com/cart-8.asp 

因此,這意味着我想去的地方的URL字符串包含任何check-8cart-8edit-8添加它。

jQuery或JavaScript的最佳方式是什麼?

var text = $('#system td.td-main').html(); 

if (text != null) 
{ 
    var newtext = text.replace("Pris","<div id=\"pricebox\">Pris").replace("mva\)","mva\)</div>"); 
    $('#system td.td-main').html(newtext); 
} 

在此先感謝。

回答

6
if(location.pathname.indexOf('check-8') > 0 || location.pathname.indexOf('cart-8') > 0 || location.pathname.indexOf('edit-8') > 0){ 
//your code here 
} 
+1

+1使用'pathname',而不是在'HREF圍繞黑客' – bobince 2010-08-28 14:48:18

2

如果你想要一個純JavaScript的解決方案,使用window.location屬性:

if (window.location.href.match(/(check|cart|edit)-8/).length > 0) { 
    // do your stuff 
} 

可以使用string.match方法來檢查,如果一個正則表達式匹配。您也可以因素出來,如果你需要知道它是哪一個:

var matches = window.location.href.match(/(check|cart|edit)-8/); 
if (matches.length > 0) { 
    var action = matches[1]; // will be check, cart or edit 
} 
+0

我應該爲/ a_regex/part放置什麼? – shin 2010-08-28 13:55:11

+0

我*猜*我現在應該工作,但我沒有測試它。 – 2010-08-28 13:55:53

+1

嗯,我做了,似乎工作! :) – 2010-08-28 13:57:42

2

或者,您可以使用以下方法:

function testForCheckEditCart() { 
    var patt = /(check|edit|cart)-8/i; 
    return patt.test(location.href); 
} 
相關問題