使用Jquery将查询字符串附加到URL
我究竟做错了什么?
- 仅在URL位置为“/MyWebsite/Example.aspx”的页面上添加“?template = PW”
- 但仅限于包含“/HelloWorld/default.aspx”的链接
没有与此链接关联的ID或类,因此我必须查找URL。
这是我的代码,但链接没有更新..我知道我很接近!
$(document).ready(function(){ if (document.location.href.indexOf('/MyWebsite/Example.aspx') > 0) { $('a[href*="/HelloWorld/default.aspx"]').append("href",$("?template=PW")) } });
$(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"); } });
使用$ .attr()编辑属性。
$ .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") } });
更换
$('a[href*="/HelloWorld/default.aspx"]').append("href",$("?template=PW"))
同
$.each( $('a[href*="/HelloWorld/default.aspx"]'), function(index, value) { $(value).attr('href', $(value).attr('href') + '?template=PW'); } );
这将使您开始,但您还应检查以确保匹配的URL中已存在查询字符串参数。
$()。append()不会改变href属性的值,它用于在每个匹配元素的末尾插入内容。 jQuery文档提供了如何使用$()。append()的示例。
你考虑过使用PURL吗? 通过PURL,我能够做到这一点:
var url = "http://localhost/some/url?item1=one&item2=two"; if ($.url(url).attr('query')) { url = url + '&newItem=new'; } else { url = url + '?newItem=new'; }
这肯定会解决你的问题。