I am trying to create a list of links dynamically using the results from a call to a web service. I have the <ul>
element in my HTML.
<ul id="myList"></ul>
And I am trying to use jQuery foreach and append to create the list items.
Given the following data:
var options = {
{href: "#", text:"text"},
{href: "#", text:"text"},
{href: "#", text:"text"},
{href: "#", text:"text"}
};
I thought I could create the list using the following script:
$each(options, function(index) {
$("#myList").append($("<li>", {}).append($("<a>", { href: options[index].href })).text(options[index].text));
});
Although it is kind of working, the text is ending up outside of the anchor elements. What I want to end up with is:
<ul id="myList">
<li><a href="#">Text</a></li>
<li><a href="#">Text</a></li>
<li><a href="#">Text</a></li>
<li><a href="#">Text</a></li>
</ul>
Can anybody tell me where I am going wrong?
Thanks.
You were close, but your syntax is slightly wrong.
var options = [
{href: "#", text:"text"},
{href: "#", text:"text"},
{href: "#", text:"text"},
{href: "#", text:"text"}
];
$.each(options, function(index) {
$("#myList").append($("<li>", {}).append($("<a>", { href: options[index].href }).text(options[index].text)));
});
You need an array of options which contain your objects. You also had a syntax error on $.each
. Example: http://jsfiddle.net/5ZDZX/1/
Try this
$.each(options, function(index) {
$("#myList").append($("<li>").append($("<a>", { href: options[index].href , text : options[index].text})));
});
I think you might be nesting the append
s incorrectly. Try:
$.each(options, function(index) {
$("#myList").append(
$("<li>", {}).append(
$("<a>", { href: options[index].href }).text(
options[index].text
)
)
);
});
The way you had it, you were adding the text
to the <li>
and not the <a>
.
That's because you're setting the .text
of the li
not the a
tag.
Also, your option
object is set up incorrectly using { }
instead of [ ]
DEMO: http://jsfiddle.net/4WTG3/
Try this:
var options = [
{href: "#", text:"text"},
{href: "#", text:"text"},
{href: "#", text:"text"},
{href: "#", text:"text"}
];
$.each(options, function(index) {
$("#myList")
.append($("<li>", {})
.append($("<a>", { href: options[index].href }).text(options[index].text)
));
});
You need array of objects and your append statement seems a bit overly complicated:
You also needed to use $.each
instead of $each
I used this succesfully
$.each(result, function (i, file) {
$("#filelist").append('<li><a target="_blank" href="' + downloadUrl + '/' + file.StaticFileId + '">' + file.ShortDesc + '</a></li>');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.