简体   繁体   English

在发送请求之前编辑href链接

[英]Edit the href link before send the request

I have this code : 我有这个代码:

<a class="myLink" href='http://www.website.it/'>Link</a>

<script type="text/javascript">
    var stringToSend = "";
    $('.myLink').click(function() {
        stringToSend="?param=1";
    }); 
</script>

and, as you can see, I'd like to add stringToSend to the href (so the request will be at http://www.website.it/?param=1 ). 并且,正如您所看到的,我想将stringToSend添加stringToSend href(因此请求将在http://www.website.it/?param=1 )。

How can I do it? 我该怎么做?

Just modify the href with new href and you are done. 只需用新的href修改href就可以了。

$('.myLink').click(function() {
    $(this).attr("href", this.href + "?param=1");
});

You should also prevent the default behavior like this: 您还应该阻止默认行为,如下所示:

var stringToSend = "";

// Use this to actually navigate to the changed Uri
$('.myLink').click(function(event) {
    event.preventDefault();
    stringToSend = "?param=1";
    window.location.href = $(this).attr('href') + stringToSend;
}); 

// Use this just to change the Href, without navigating to uri
$('.myLink').click(function(event) {
    event.preventDefault();
    stringToSend = "?param=1";
    var newUri = $(this).attr('href') + stringToSend;
    $(this).attr("href", newUri);
});

When clicking, you could stop the current URL, and navigate to another: 单击时,您可以停止当前URL,然后导航到另一个URL:

var stringToSend = "";
$('.myLink').click(function() {
    stringToSend="?param=1";
    window.location.href = $(this).attr('href') + stringToSend; // navigate to new URL
    return false; // abort navigation to URL from <a>
}); 

Just set the window.location on your click, and return false to prevent the default behaviour. 只需在单击时设置window.location,然后返回false以防止出现默认行为。

A such: 一个这样的:

<a class="myLink" href='http://www.website.it/'>Link</a>

<script type="text/javascript">
    var stringToSend = "";
    $('.myLink').click(function() {
        window.location.href = this.href + "?param=" + stringToSend;
        return false;
    }); 
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM