简体   繁体   English

使用JQuery从href属性字符串中提取值

[英]Extract values from href attribute string using JQuery

I would like to extract values from href attribute string using JQuery 我想使用JQuery从href属性字符串中提取值

$(this).attr("href")

will give me 会给我的

?sortdir=ASC&sort=Vendor_Name

What i need is these values parsed into an array 我需要的是将这些值解析为数组

myArray['sort']

myArray['sortdir']

Any ideas? 有任何想法吗? Thanks! 谢谢!

BTW , I saw somewhere else on SO the following similar idea to be used with a query string. 顺便说一句,我在其他地方看到了以下与查询字符串一起使用的类似想法。 I could not tweak it for my needs just yet. 我还不能根据我的需要调整它。

var urlParams = {};
    (function () {
        var match,
    pl = /\+/g,  // Regex for replacing addition symbol with a space
    search = /([^&=]+)=?([^&]*)/g,
    decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
    query = window.location.search.substring(1);

        while (match = search.exec(query))
            urlParams[decode(match[1])] = decode(match[2]);
    })();

Try the following: 请尝试以下方法:

var href = $(this).attr("href")
href = href.replace('?', "").split('&');

var myArr = {};
$.each(href, function(i, v){
   var s = v.split('=');
   myArr[s[0]] = s[1];    
});

DEMO DEMO

Perhaps is there a better solution but to be quick I should have do something like that 也许有更好的解决方案,但要快点我应该做那样的事情

var url = $(this).attr("href");
url = url.replace("?sortdir=", "");
url = url.replace("sort=", "");
myArray['sort'] = url.split("&")[1]; // Or use a temporary tab for your split
myArray['sortdir'] = url.split("&")[0];

That solution depends if your url is still like ?sortdir=ASC&sort=Vendor_Name 该解决方案取决于您的网址是否仍然像?sortdir = ASC&sort = Vendor_Name

You could use jQuery BBQ's deparam function from here: 你可以从这里使用jQuery BBQ的deparam函数:

http://benalman.com/code/projects/jquery-bbq/examples/deparam/ http://benalman.com/code/projects/jquery-bbq/examples/deparam/

Try this 尝试这个

function getURLParameter(name, string) {
    return decodeURI(
        (RegExp(name + '=' + '(.+?)(&|$)').exec(string)||[,null])[1]
    );
}

var string = $(this).attr("href");

alert(getURLParameter("sort",string));

Demo here http://jsfiddle.net/jbHa6/ You can change the var string value and play around. 在这里演示http://jsfiddle.net/jbHa6/您可以更改var字符串值并进行播放。

EDIT 编辑

Removed the second example, since that code is not that good and does not serve the purpose. 删除了第二个示例,因为该代码不是那么好,不能达到目的。

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

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