【问题标题】:Get parameter values from href in jquery从jquery中的href获取参数值
【发布时间】:2013-03-24 17:27:45
【问题描述】:

脚本

 <a href="#?cat=MT&typ=1" data-reveal-id="reveal_popup" onclick="pop();" data-closeonbackgroundclick="false" data-dismissmodalclass="close-reveal-modal">due today</a>
 <a href="#?cat=MT&typ=2" data-reveal-id="reveal_popup" onclick="pop();" data-closeonbackgroundclick="false" data-dismissmodalclass="close-reveal-modal">due in 2 days</a>

 <div id="reveal_popup" class="reveal-modal">
 <div id="popup"></div>
 <a class="close-reveal-modal">&#215;</a>
 </div>

function pop() {

 var cat=**value of cat parameter in href**
 var type=**value of typ parameter in href**

 $.ajax({
       type:'post',
       url:site_url()+'/event/deleteEventSingle',
       data:{'cat':cat,'type':typ},
        async:false,
         success:function(result){}
        });
}

在这种情况下,当用户单击 href 时,会出现相同的弹出窗口,其中包含不同的数据。实际上有 10 多个 href,我正在尝试在弹出窗口中显示带有用户输入数据的日历。这取决于两个参数 cat 和 typ,如 href 所示。

要求

每个 href 都有自己的 cat 和 typ 值。单击 href 时,我希望使用 jquery 获取单击的 href 的 cat 和 typ 值,以便我可以在 ajax 中传递这些变量。

var cat=**value of cat parameter in href**
var type=**value of typ parameter in href**

试过

How to get the parameters of an href attribute of a link from the click event object

【问题讨论】:

  • 我建议你使用 data-* 属性。像这样` 今天到期 `.
  • @Ravi: 我怎样才能使用这个获取值
  • 你可以使用jquery data() 方法。

标签: jquery href


【解决方案1】:

你可以做一些如下的事情

$('a').bind('click',function(){
    var url = ($(this).attr('href'));
    var cat = getURLParameter(url, 'cat');
    var typ = getURLParameter(url, 'typ');
    //calling the ajax function
    pop(cat, typ)
});


function getURLParameter(url, name) {
    return (RegExp(name + '=' + '(.+?)(&|$)').exec(url)||[,null])[1];
}

function pop(cat, typ) {

    $.ajax({
       type:'post',
       url:site_url()+'/event/deleteEventSingle',
       data:{'cat':cat,'type':typ},
        async:false,
         success:function(result){}
    });
}

查看 Live fiddle http://jsfiddle.net/mayooresan/aY9vy/ 中的示例

【讨论】:

  • 当你点击它返回正确值的链接时你检查过小提琴吗..
  • 你能在没有 ajax 的情况下使用同样的方法吗?我在下面的链接中问过同样的问题请帮助我stackoverflow.com/questions/45663358/…
【解决方案2】:

试试这个:

function getUrlParams(url) {
    var params = {};
    url.substring(1).replace(/[?&]+([^=&]+)=([^&]*)/gi,
            function (str, key, value) {
                 params[key] = value;
            });
    return params;
}

用法:

function pop(e) {
     var url = $(e.target).attr("href");
     var params = getUrlParams(url); 

     var cat= params["cat"];
     var type= params["typ"];

     alert(cat);
     alert(type);    
}

Working Fiddle

【讨论】:

  • 当我提醒猫时,我得到的价值是未定义的
  • 是否需要子字符串调用?在我看来,它只是绕过了演示中 URL 的 # 部分。
猜你喜欢
  • 1970-01-01
  • 2019-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-11
  • 1970-01-01
  • 2017-09-05
  • 2015-04-05
相关资源
最近更新 更多