简体   繁体   中英

How to find url parameters in JavaScript, or jQuery, then apply an event listener?

So I have this url: /somepage/goes-here/something?image=main_image.jpg&type=shirt

How do I get out the two different attributes to then apply an eventListener to them?

I've tried the following:

var originalUrl = window.location.href
var type = originalUrl.search.get("type");
var image = originalUrl.search.get("image");

But I don't really think I'm getting the attributes with .search.get. Plus it errors with .search.get("type") is not a function.

I've also tried the following:

function getParam(param){
return new URLSearchParams(window.location.search).get(type);
}

I'm honestly not too familiar with URLSearchParams but wouldn't it be similar to above? How would I get both params here?

I also have for jQuery, which I'm not familiar with, the following:

$(function(){
$.url.attr('image')
$.url.attr('type')
});

This one...no idea. But it fails as it's not bringing in the url.

Alternatively you could construct a URL object and grab them as so:

var originalUrl = new URL(location.href);
var type = originalUrl.searchParams.get('type');
var image = originalUrl.searchParams.get('image');

One thing to note. As of this post it seems that it's not supported by IE .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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