admin管理员组文章数量:1296254
I currently have this bit of jQuery I am using to append a URL with some location information.
jQuery('a').attr('href', function() {
return this.href + "&location=/123/abc";
});
My issue is most links have a ? in which makes for the use of the above & ok. There are a select few that dont. I am looking to check the url to see if there is a ?. If there is I want to use "&location=/123/abc", if there is no ? I will need to use "?location=/123/abc"
I am not the best with if/else statements. Any help would be appreciated.
if (thereIsA?InTheUrl) {
return this.href + "&location=/123/abc";
} else {
return this.href + "?location=/123/abc";
}
Something like that, just not sure oh to write it.
I currently have this bit of jQuery I am using to append a URL with some location information.
jQuery('a').attr('href', function() {
return this.href + "&location=/123/abc";
});
My issue is most links have a ? in which makes for the use of the above & ok. There are a select few that dont. I am looking to check the url to see if there is a ?. If there is I want to use "&location=/123/abc", if there is no ? I will need to use "?location=/123/abc"
I am not the best with if/else statements. Any help would be appreciated.
if (thereIsA?InTheUrl) {
return this.href + "&location=/123/abc";
} else {
return this.href + "?location=/123/abc";
}
Something like that, just not sure oh to write it.
Share Improve this question edited Jun 13, 2011 at 22:59 Francisc 80.5k65 gold badges185 silver badges278 bronze badges asked Jun 13, 2011 at 22:54 MichaelMichael 4841 gold badge8 silver badges20 bronze badges4 Answers
Reset to default 7 jQuery('a').attr('href', function() {
return (this.href.indexOf("?") >= 0) ? this.href + "&location=/123/abc" : this.href + "?location=/123/abc";
});
Michael.
Use JavaScript's indexOf() function.
Like this:
if(this.href.indexOf('?')>=0){//PLACE MAGIC HERE}
How it works is this:
Returns position of matched string if it finds it.
Returns -1 if it does not find it, hence >=0
. Position 0 is the first character of a string.
Details here:
https://developer.mozilla/en/JavaScript/Reference/Global_Objects/String/indexOf
var str = window.location.href;
if (str.indexOf('?' >= 0) {
return str + "&location=/123/abc"; //there's a ?
} else {
return str + "?location=/123/abc"; //no ?
}
if (this.href.indexOf("?") >= 0)
本文标签: javascriptChecking href for presence of a query string in jQueryStack Overflow
版权声明:本文标题:javascript - Checking href for presence of a query string in jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741634685a2389572.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论