2012-10-26 98 views
0

我一直在寻找这在谷歌恩SO,我得到的功能,我想从网址(link to article)获取查询参数。
但我无法找到我的问题的答案,我相当积极的是它应该是易于修复,我甚至觉得愚蠢问,但我无法找到这个具体的答案。获取网址查询,而返回假

当我点击一个链接,并在jquery中捕获该点击时,该函数返回false(我不想刷新),所以我想要的参数不会被解析为url。我如何得到这些?

CURRENT URL: index.php?page=search&action=searchAll 
<h4 class="videoLink"><a href="index.php?page=search&amp;action=playVideo&amp;isAjax=true&amp;v={$result.link}" class="{$result.link}">{$result.title}</a></h4> 

jQuery的简化

$('.videoLink').click(playVideo); 

function playVideo(){ 
    url = getUrlVars(); 
    return false; 
} 

function getUrlVars(){ 
    var vars = [], hash; 
    var hashes = window.location.href.slice(window.location.href.indexOf('?')+1).split('&'); 

    for(var i = 0; i < hashes.length; i++){ 
     hash = hashes[i].split('='); 
     vars.push(hash[0]); 
     vars[hash[0]] = hash[1]; 
    } 
return vars; 
} 

所以当我追踪URL,我只得到PARAMS:页&行动

+1

你的网址是错误的..你永远不会关闭'href'标签 –

+0

这就是我的不好,因为最后一个参数是一个聪明的变量,我改变了它,只是忘了把“后退”。我的代码是100%有效的 – Empi

回答

0

返回false之前,你可以得到该链接并提取参数..

$('a').click(function(e){ 

    var href = this.href; 
    var params = {}; 
    // remove the part of the href up to the first ? character 
    // and then split the remaining at the & character 
    // loop the resulting list of somekey=somevalue 
    // and split at the = and store in the params variable 
    $.each(href.replace(/^.*?\?/gi,'').split('&'), function(i,val){ 
     var parts = val.split('='); 
     params[parts[0]] = decodeURIComponent(parts[1]); 
    }); 

    // do what you want with the params here 

    return false; 
}); 

更新

如果你希望你的代码与传递给它的浏览器位置以及自定义网址的工作,你可以把它改成

function getUrlVars(href){ 
    var vars = [], 
     hash, 
     url = href || window.location.href; 

    var hashes = url.slice(url.indexOf('?')+1).split('&'); 

    for(var i = 0; i < hashes.length; i++){ 
     hash = hashes[i].split('='); 
     vars.push(hash[0]); 
     vars[hash[0]] = hash[1]; 
    } 
return vars; 
} 

,并调用它

function playVideo(){ 
    url = getUrlVars(this.href); 
    return false; 
} 
+0

我这样做,返回false总是在我的声明结束。我将更新我的代码,以便更清楚我在做什么 – Empi

+0

@empi,您的代码尝试从URL中获取参数。但是,既然你返回false,url不会改变。你需要从链接的'href'属性中提取参数,或者使用我提供的代码,或者改变你的函数来使用作为参数传递给它的任意url。 –

+0

@Empi,更新了你的答案自己的方法.. –