jQuery colorbox - get url parameter from clicked link
I am using Colorbox to load a contact form within an iframe.
However, I want the Colorbox url to be different than the html one, to serve up a different contact page for JS and non-JS users.
I do need to get the url parameter from the exact clicked link though.
HTML Code:
<a href="contact?id=XX" class="enquiryForm">
Colorbox code:
$(document).ready(function(){
$('.enquiryForm').colorbox({height:600, width:800, iframe:true, href: 'colorboxcontact?id=XX'});
});
Where 'contact' is the non-JS page and 'colorboxcontact' is the page to be loaded in the Colorbox iframe.
How can I extract the url parameter from the clicked link, and then add it to the 'colorboxcontact' href value in my jQuery call?
* EDIT *
Ok I've arrived at the following but still don't have it working. Can anyone point out where I am going wrong?
$('.enquiryForm').colorbox({
height:600,
width:800,
iframe:true,
href: $('.enquiryForm').each(function() {
newhref = 'colorboxcon开发者_如何学编程tact' + $(this).attr('href').split("?")[3];
$(this).attr('href', newhref);
});
});
To get specific query string info for url string you need this function found at:
How can I get query string values in JavaScript?
slightly modified:
function getParameterByName(url, name)
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec(url);
if( results == null )
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
so then you will end up with something like this:
$('.dialog-open').each(function() {
$(this).colorbox({
height: 600,
width: 800,
iframe: true,
href: "contact?id=" + getParameterByName($(this).attr("href"), "id")
});
});
Use a .each()
to get the value, like this:
$(document).ready(function(){
$('.enquiryForm').each(function() {
$(this).colorbox({
height: 600,
width: 800,
iframe: true,
href: $(this).attr("href")
});
});
});
.each()
gives you access to each <a>
as you loop over them via this
. If you don't care if it's a fully qualified url or not, you can replace $(this).attr("href")
with this.href
(IE will fully qualify this), like this:
$(function(){
$('.enquiryForm').each(function() {
$(this).colorbox({ height: 600, width: 800, iframe: true, href: this.href });
});
});
I think perhaps a simple approach would be to set the href to a function that returns the link.
$(document).ready(function(){
$('.enquiryForm').colorbox({
height:600,
width:800,
iframe:true,
href: function(){
return $(this).attr('href');
}
});
});
精彩评论