in my function in a jquery, i try to split a long string. i think that when splitting, the result is an array. so i used .each to get the values of splitted string. however, it is not showing anything. where is my error in this syntax:
function DisplayList(data) {
$.each(data.split('|'), function (index, value) {
$(".listDisplay").html('<p>' + value + '</p>');
});
};
when i put index in the .html() instead of value, i am shown the number of elements in the array. it’s supposed to show something like [0], [1], [2]… right?
what i really want is to show in a paragraph form the contents of my splitted string… (.listDisplay is a div)
The line:
overwrites the contents of “.listDisplay” with the current
value. So each iteration of the$.each()overwrites the previous value and then when the$.each()finishes “.listDisplay” will hold whatevervaluewas from the final iteration.Try changing it to:
That will add a new paragraph to the end of “.listDisplay” rather than overwriting the existing contents. So the
.each()will add a new paragraph for each item in the array returned bydata.split('|').(You may want to add
$(".listDisplay").empty()or$(".listDisplay").html("")just before the$.each()to clear any existing contents in your div before adding the new paragraphs.)Another approach is to do it in one line without the
$.each():