簡體   English   中英

如何為location.href.match設置更具體的網址?

[英]How do I make a more specific url for location.href.match?

我正在使用一系列if語句來使用以下內容在論壇上操作CSS:

if(location.href.match(/(showforum=3)/i) != null) {
$(document).ready(function(){
$("#topimg").addClass("announce");
});}

該代碼工作得很好,但是除非以其他方式編碼,否則其他所有以3開頭的showforum都會顯示此圖像。 所以我的問題是如何使我的位置更精確,以便僅更改3而不更改3x? 甚至可以使用這種編碼嗎?

更改您的正則表達式,以便也檢查“值的邊界”:

var pattern = /showforum=3(?=&|$)/i;
if (pattern.test(location.href)) {
  ...
}

請注意測試表達式中的伴隨變化:如果僅需要查找某些字符串是否與模式匹配,則應使用regexp.test(string)語法,而不是string.match(regexp) !== null

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

if( getParameterByName("showforum") == 3 ){
    //........

}

參考

如何獲取JavaScript中的查詢字符串值?

暫無
暫無

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

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