如何使用jQuery初始化href

4
我正在尝试使用以下代码来追加我的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个回答

2

一个简单的解决方案是在dom就绪时读取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
当您点击按钮时,单击事件将被调用。 单击事件函数会将现有的URL与国家代码连接起来,因此现有的URL会追加国家代码。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接