使用 Jquery 将查询字符串附加到 URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16408692/
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
Append Query String to URL with Jquery
提问by Evan
What am I doing wrong?
我究竟做错了什么?
- Only on pages with the URL location of "/MyWebsite/Example.aspx" append "?template=PW"
- But only to links that contain "/HelloWorld/default.aspx"
- 仅在 URL 位置为“/MyWebsite/Example.aspx”的页面上附加“?template=PW”
- 但仅限于包含“/HelloWorld/default.aspx”的链接
There is no ID or classes associated to this link, so I have to look for the URL.
没有与此链接关联的 ID 或类,因此我必须查找 URL。
This is my code, but the links are not updating.. I know I'm close!
这是我的代码,但链接没有更新..我知道我很接近!
$(document).ready(function(){
if (document.location.href.indexOf('/MyWebsite/Example.aspx') > 0)
{
$('a[href*="/HelloWorld/default.aspx"]').append("href",$("?template=PW"))
}
});
采纳答案by Okan Kocyigit
$(document).ready(function(){
if (document.location.href.indexOf('/MyWebsite/Example.aspx') > 0)
{
var $el = $('a[href*="/HelloWorld/default.aspx"]');
$el.attr("href", $el.attr("href")+ "?template=PW");
}
});
回答by Flo Schild
Use $.attr() to edit an attribute.
使用 $.attr() 编辑属性。
$.append() is used to insert an html child node inside your element.
$.append() 用于在元素中插入一个 html 子节点。
$(document).ready(function(){
if (document.location.href.indexOf('/MyWebsite/Example.aspx') > 0)
{
var href = '/HelloWorld/default.aspx';
$('a[href*="' + href + '"]').attr("href", href + "?template=PW")
}
});
回答by shaz3e
This would definitely solve your problem as it did mine.
这肯定会像我一样解决您的问题。
<script type="text/javascript">
var querystring = 'MyString'; // Replace this
$('a').each(function(){
var href = $(this).attr('href');
href += (href.match(/\?/) ? '&' : '?') + querystring;
$(this).attr('href', href);
});
</script>
回答by rtcherry
Replace
代替
$('a[href*="/HelloWorld/default.aspx"]').append("href",$("?template=PW"))
With
和
$.each(
$('a[href*="/HelloWorld/default.aspx"]'),
function(index, value) {
$(value).attr('href', $(value).attr('href') + '?template=PW');
}
);
That will get you started, but you should also check to make sure there isn't a query string parameter already in the matched URL.
这将使您开始,但您还应该检查以确保匹配的 URL 中没有查询字符串参数。
$().append()
doesn't alter the value of the href attribute, it is used to insert content at the end of each matched element. The jQuery documentationhas examples of how to use $().append()
.
$().append()
不会改变 href 属性的值,它用于在每个匹配元素的末尾插入内容。在jQuery的文档有如何使用的例子$().append()
。