I want to change the variable values in all links on the page.
If the links looks like this:
<a href="http://www.mypage.com?type=iPhone&userId=1">The 1 link</a>
<a href="http://www.mypage2.com?type=iPhone&userId=1">The 2 link</a>
I want to change type=iPhone to type=Android. But I don’t know how to find the type=iPhone so I can replace it?
What is the best way of doing this?
Thanks.
Ok, this is my real code.
What Im trying to do is to check for the user agent and change the appType=iPhone if it is an android.
var ua = navigator.userAgent;
if (ua.indexOf("Android") >= 0) {
var androidversion = parseFloat(ua.slice(ua.indexOf("Android") + 8));
if (androidversion < 4.0) {
alert("You have an old Android");
}
var apptype='appType=Android';
alert(apptype);
$("a[href*='appType=iPhone']").attr("href", function () {
return this.href.replace("appType=iPhone", "appType=Android");
});
}
else
{
var apptype='appType=iPhone';
alert(apptype);
}
And with this it is not changing the appType=iPhone at all, I dont know what Im missing?
This can be done the way you imagine, but seriously – question if that is the best way to achieve your goal.
Using jQuery, you can find elements using an attribute-contains-selector:
The
*=says “attribute contains”Then you can just replace the href:
However, you should consider there may be a better way to do this. For example if you remove that
type=iPhoneattribute from thehrefand instead decide whichtype=*to append when the user clicks the link, then you dont need to do all that messing about finding and replacing.For example, starting with this HTML:
Then assuming a variable which contains which
typeis active:Use this jQuery:
Live example of this technique: http://jsfiddle.net/K7UNg/1/