Href Links Dymamically
I have some links开发者_JAVA百科 in an json file
<code>
"links": [
{"link": "http://www.google.com/",
"id": "1"
},
{"link": "http://www.poogle.com/",
"id": "2"
},
{"link": "http://www.foogle.com/ ",
"id": "3"
},
]
</code>
on a webpage, I will like a js function or script that will write in the url href dynamically
So if im on a page and the href is
<a href id=”1”> </a>
it should be able to write in google.com into that ahref.
Also is this the best approach to take, should I use Id? Or something else?
Your insight will be helpful
UPDATED
JSON FILE:
{"links":
[
{"link": "google.com",
"id": "1"
},
{"link": "yahoo.com",
"id": "2"
},
{"link": "msn.com",
"id": "3"
},
{"link": "mash.com",
"id": "4"
},
{"link": "facebook.com",
"id": "5"
}
]
}
JS
for (var i = 0; i < linksObj.links.length; i++) {
var linkObj = linksObj.links[i];
var elem = document.getElementById(linkObj.id);
if (elem) {
elem.href = linkObj.link;
elem.innerHTML = linkObj.link;
}
}
HTML
<a id='1'></a><br>
<a id='2'></a>
First off, IDs beginning with a number are not valid - change them to have a letter in front :)
Other than that though, this would do:
for (var i = 0; i < links.length; i++) {
var link = links[i];
$('#' + link.id).attr('href', link.link);
}
EDIT
Also, as John Hartsock mentions above, make sure you use a standard double quote to surround your attribute values, not the curly one shown in your original code.
here's the way to do it if you don't want to use jQuery:
for (var i = 0; i < links.length; i++) {
var link = links[i];
document.getElementById(link.id).setAttribute('href', link.link);
}
var linksObj = {"links": [
{"link": "http://www.google.com/",
"id": "1"
},
{"link": "http://www.poogle.com/",
"id": "2"
},
{"link": "http://www.foogle.com/ ",
"id": "3"
},
]};
for (var i = 0; i < linksObj.links.length; i++) {
var linkObj = linksObj.links[i];
var elem = document.getElementById(linkObj.id);
if (elem) {
elem.href = linkObj.link;
elem.innerHTML = linkObj.link;
}
}
Example
精彩评论