简体   繁体   中英

Pass a js variable to a href

I'm working on some links and I can't get it to work! I would know how it works with php but I suck in js :P

So I use fancybox for some simple forms. But I need to pass the current url of document to that page, so we know where the one who filled the form in comes from! Every url is build like

example.com/city

So I need that city, so I can pass it to the iFrame, otherwise I need to make a page for each city...

<a class="button fancybox.iframe" id="offerte" data-fancybox-type="iframe" href="offerte.php?page=city">Offerte aanvragen <span>»</span></a>

Something like this works, but I can't get in the href the right way!

document.write(document.URL);

How can I get the page link and pass it in the href??

You need to use location.href property. If don't need domain and protocol there you can use location.pathname .

Read more about Location object at MDN.

You mentioned that you used jQuery in your tags, so w/ jQuery you can do this in that way:

$( '#offerte' ).attr( 'href', location.pathname );

and if you need to pass it as argument try this:

$( '#offerte' ).attr( 'href', 'offerte.php?page=' + location.pathname );

请在此处使用window.location更多信息http://www.w3schools.com/jsref/obj_location.asp

你可以试试,

document.getElementById("offerte").setAttribute("href",location.href);

Please try the following code:

Assumption url: example.com/city --> example.com/paris

var u=window.location.href;
var city=u.substring(u.lastIndexOf("/")+1);
document.getElementById("offerte").setAttribute("href","offerte.php?page="+city);

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