简体   繁体   English

如果URL具有特定的字符串,也可以使用jQuery或Javascript作为另一个字符串的一部分来运行函数

[英]I need to run a function if the URL has a specific string that can also come up as part of another string using jQuery or Javascript

I need to write a function to perform an action only if the URL has a specific string. 仅在URL具有特定字符串的情况下,我才需要编写函数来执行操作。 The issue that I am finding is that the string can come up in multiple instances as part of another string. 我发现的问题是该字符串可以在另一个字符串的多个实例中出现。 I need the function to run when the string is ONLY "?page=1". 我需要在字符串仅为“?page = 1”时运行的函数。 What I am finding is that the function is also being run when the string contains a string like "?page=10" , "?page=11" , "?page=12" , etc... I only need it to be done if the string is "?page=1" - that's it. 我发现的是,当字符串包含诸如“?page = 10”,“?page = 11”,“?page = 12”等字符串时,该函数也正在运行……我只需要它如果字符串为“?page = 1”,则完成-就是这样。 How do I do that? 我怎么做? I've tried a couple of different ways, but it does not work. 我尝试了几种不同的方法,但是它不起作用。 Any help is appreciated. 任何帮助表示赞赏。 Here is the latest code that I have used that is close...but no cigar. 这是我使用过的最新代码,很接近,但是没有雪茄。

var location = window.location.href; 
if (location.indexOf("?page=1") > -1){
//Do something
};
if(location .indexOf("?page=1&") != -1 || (location .indexOf("?page=1") + 7 == i.length) ) {

}

?page is a GET parameter. ?page是GET参数。 It doesn't necessarily have to be first in the URL string. 它不一定必须在URL字符串中排在第一位。 I suggest you properly decode the GET params and then base your logic on that. 我建议您正确地解码GET参数,然后基于此逻辑。 Here's how you can do that: 这是您可以执行的操作:

function unparam(qs) {
    var params = {},
        e,
        a = /\+/g,
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); };

    while (e = r.exec(qs)) {
        params[d(e[1])] = d(e[2]);
    }

    return params;
}

var urlParams = unparam(window.location.search.substring(1));

if(urlParams['page'] == '1') {
    // code here
}

Alternatively, a regex with word boundaries would have worked: 另外,带有单词边界的正则表达式也可以工作:

if(/\bpage=1\b/.test(window.location.search)) {
    // code here
}

You could look at the character immediately following the string "?page=1" in the url. 您可以在网址中紧随字符串“?page = 1”之后的字符中查看字符。 If it's a digit,you don't have a match otherwise you do. 如果是数字,则没有匹配项,否则。 You could trivially do something like this: 您可以琐碎地做这样的事情:

  var index = location.indexOf("?page=1"); //Returns the index of the string
  var number = location.charCodeAt(index+x); //x depends on the search string,here x = 7
  //Unicode values for 0-9 is 48-57, check if number lies within this range

Now that you have the Unicode value of the next character, you can easily deduce if the url contains the string you require or not. 现在您有了下一个字符的Unicode值,可以轻松推断出url是否包含所需的字符串。 I hope this points you in the right direction. 我希望这可以为您指明正确的方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM