javascript 在发送请求之前编辑 href 链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7159207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Edit the href link before send the request
提问by markzzz
I have thiscode :
我有这个代码:
<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
到 href(因此请求将位于http://www.website.it/?param=1)。
How can I do it?
我该怎么做?
回答by ShankarSangoli
Just modify the href
with new href
and you are done.
只需href
使用 new修改即可href
。
$('.myLink').click(function() {
$(this).attr("href", this.href + "?param=1");
});
回答by DenisPostu
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);
});
回答by pimvdb
When clicking, you could stop the current URL, and navigate to another:
单击时,您可以停止当前 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>
});
回答by TJHeuvel
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>