如何使用jQuery初始化href


How to initialize href using jQuery

我正试图使用下面的代码附加我的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"

我该如何解决这个问题?

一个简单的解决方案是在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);
    });
});

单击按钮时,单击事件将调用。click事件函数具有与现有url的串联。因此,现有的url附加了国家代码