函数使用javascript和Jquery检索url变量? [英] function to retrieve url variables using javascript and Jquery?

查看:65
本文介绍了函数使用javascript和Jquery检索url变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的脚本中有一个简单的列表显示了要编辑的链接

in my script there a simple list shows links for editing

<ul>
<li><a href="edit.php?id=5" class="edit">click here</a></li>
<li><a href="edit.php?id=5" class="edit">click here</a></li>
<li><a href="edit.php?id=5" class="edit">click here</a></li>
<li><a href="edit.php?id=5" class="edit">click here</a></li>
</ul>

我需要的是读取变量id所以我可以通过.ajax调用发送它我尝试过这个函数

what i need is to read the variable id so i can send it through .ajax call and i tried this function

$(document).ready(function(){
    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;
     }
     $('.edit').click(function(){
         var test = getUrlVars()["id"];
         alert(test);
     });
});

当我点击链接时,警告信息显示 undefined

When I clicked on the link, the alert message shows undefined.

我尝试了另一个功能:

$(document).ready(function(){
    var urlParams = {};
    (function () {
        var match,
               pl = /\+/g,  // Regex for replacing addition symbol with a space
           search = /([^&=]+)=?([^&]*)/g,
           decode = function(s) { 
               return decodeURIComponent(s.replace(pl, " ")); 
           },
           query  = window.location.search.substring(1);
           while (match = search.exec(query))
               urlParams[decode(match[1])] = decode(match[2]);
     })();
     $('.edit').click(function(){
         var test = urlParams["id"];
         alert(test);
     });
 });

...但即便如此,也会显示警告信息 undefined

... but even this also shows up the alert message undefined.

推荐答案

您尝试过的方法不会将URL作为参数,而是解析当前网址参数(即您兄弟中的网址)。只需修改这样的第一个方法就可以了:

The methods your tried don't take an URL as argument, but parse the current URL parameters (i.e. the URL within your brother). Just modify the first method like this to make it work:

$(function() {
    function getUrlVars(url) {
        var vars = [], hash;
        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;
    }
    $('.edit').click(function() {
        var href = $(this).attr("href");
        var test = getUrlVars(href)["id"];
        alert(test);
    });
});

附注:你也可以修改第二个,两个都做同样的工作。

Side note: you could also modify the second one, both of them do the same job.

这篇关于函数使用javascript和Jquery检索url变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆