通过Javascript从href属性获取查询字符串

时间:2013-10-28 22:09:23

标签: javascript

我正在构建一个使用带有HTML回退的AJAX的界面。我正在设置所有<a>标签,以便在没有AJAX的情况下工作,如果启用了Javascript,每个链接都会附加一个“onclick”函数,将相同的查询字符串发送到我的不同页面服务器

我的原始链接如下所示:

<a class="ajax" href="http://example.com/page?key1=value1&key2=value2">Link</a>

如何通过Javascript从上面的href链接中检索“key1 = value1&amp; key2 = value2”作为字符串?我将制作看起来像http://example.com/ajax?key1=value1&key2=value2

的AJAX请求

3 个答案:

答案 0 :(得分:1)

您可以将click处理程序附加到各个链接:

var links = document.getElementsByTagName('a');
var index;
for (index = 0; index < links.length; ++index) {
    links.onclick = linkClickHandler;
}
function linkClickHandler() {
    var x = this.href.indexOf('?');
    var query = x >= 0 ? this.href.substring(x + 1) : null;
    if (query) {
        // Do the ajax thing...
        // (your code here)
        // ...and prevent the link from being followed
        return false;
    }
}

...或(这可能更好)到document本身:

document.onclick = function(e) {
    var target, x, query;

    e = e || window.event;
    target = e.target;
    if (target.tagName.toUpperCase() === "A") {
        x = target.indexOf('?');
        query = x >= 0 ? target.substring(x + 1) : null;
        if (query) {
            // Do the ajax thing...
            // (your code here)
            // ...and prevent the link from being followed
            return false;
        }
    }
};

在任何一种情况下,在现代浏览器中,您可能希望使用addEventListener而不是onclick,并在事件对象上调用preventDefault。但IE8仍然使用attachEvent而不是addEventListener

(来自return false;等老式DOM0事件处理程序的onclick会阻止事件的默认操作; details。)

答案 1 :(得分:0)

此示例代码应足以帮助您解析所需内容。请注意,我在锚点中添加了一个ID,以便于访问。

<!DOCTYPE html>
<HTML>
<HEAD>
<SCRIPT type="text/javascript">
function parse() {
  var el = document.getElementById("foo");
  var href = el.href;
  var pos = href.indexOf("?");
  alert(href.substring(pos+1));
}

</SCRIPT>
</HEAD>
<BODY bgcolor="white" onLoad="parse()">
<a id="foo" class="ajax" href="http://example.com/page?key1=value1&key2=value2">Link</a>
</BODY>
</HTML>

答案 2 :(得分:0)

TL;博士

查看您对其他答案的评论,这就是您所需要的

linkElement.search.substr(1)


<小时/>

答案......

您可以访问与window.location相同的属性。

对于href的查询字符串,它将是(document.querySelector('a#mylink')).search

其他可访问的属性

.hash
.host
.hostname
.href
.origin
.pathname
.port
.protocol
.search

在您的情况下,对于页面上的所有链接,请使用此小脚本

*我只选择带有实际href的链接。

[].forEach.call(document.querySelectorAll('a[href]'), function(el) {
    var queryString = el.search.substr(1)
    el.onclick = function(e){
        e.preventDefault() // don't redirect and stuff...
        // do the magic here with the queryString
    }
})
相关问题