如何使用jQuery初始化href

时间:2015-02-23 06:16:56

标签: php jquery jquery-ui

我尝试使用以下代码附加我的href属性值

$(document).ready(function() { 
     jQuery("#help_url").click(function(){
        var href = $(this).attr('href');
        alert(href);
        var txt_api_key = $('#txt_api_key').val();
        var txt_postcode = $('#txt_postcode').val();
        var txt_countrycode = $('#txt_countrycode').val();
        $('a#help_url').attr('href', href+txt_postcode+"/"+txt_countrycode+"?api_key="+txt_api_key);
    });
});

这是完美的。但问题是在第一次点击后,链接将变为http://api.fastway.org/v1/psc/pickuprf/2148/1?api_key=5340c900251a6105a19a58a1590472bb,并在我更改" txt_countrycode"之后的下一次点击如果没有价值或者没有任何价值,那就变成http://api.fastway.org/v1/psc/pickuprf/2148/1?api_key=5340c900251a6105a19a58a1590472bb2148/1?api_key=5340c900251a6105a19a58a1590472bb

即再次添加" href + txt_postcode +" /" + txt_countrycode +"?api_key =" + txt_api_key"

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

一个简单的解决方案是在dom ready中读取href的值并在点击处理程序中使用它,以便href具有非更新值

$(document).ready(function () {
    var href = jQuery('#help_url').attr('href');
    jQuery("#help_url").click(function () {
        alert(href);
        var txt_api_key = $('#txt_api_key').val();
        var txt_postcode = $('#txt_postcode').val();
        var txt_countrycode = $('#txt_countrycode').val();
        $('a#help_url').attr('href', href + txt_postcode + "/" + txt_countrycode + "?api_key=" + txt_api_key);
    });
});

答案 1 :(得分:1)

单击该按钮时,将调用click事件。 click事件功能与现有url连接。现有的url附加国家代码