Reputation: 3
I am trying to dynamically insert image source but it is having some problems with the orientation of the image. My code looks like this.
$.each(mydata, function(index, data){
$('#data').append('<li>+ <img src='+mydata[index].team.crestUrl +'>
<a id="to_details" href="#">'+'<span id="'+ index +'" class="ui">' +
mydata[index].team.name +'</span></a></li>');
With below change the image does not appear at all:
$.each(mydata, function(index, data){
$('#data').append('<li> <img src='+mydata[index].team.crestUrl +'>
<a id="to_details" href="#">'+'<span id="'+ index +'" class="ui">' +
mydata[index].team.name +'</span></a></li>');
An example is given in the images
I tried many ways but its still not working for me.
Upvotes: 0
Views: 166
Reputation: 164776
Building HTML strings is usually pretty messy and can lead to problems with character encoding and string literal termination (as you are seeing).
I find it best to construct elements instead of strings. For example
$('#data').append(mydata.map(({ team }, index) => $('<li>').append([
$('<img>', { src: team.crestUrl }),
$('<a>', { id: 'to_details', href: '#' }).append($('<span>', {
id: index,
class: 'ui',
text: team.name
}))
])))
const mydata = [{
team: { name: 'Team #1', crestUrl: 'https://via.placeholder.com/100x50?text=Team+1+Crest' },
}, {
team: { name: 'Team #2', crestUrl: 'https://via.placeholder.com/100x50?text=Team+2+Crest' },
}]
$('#data').append(mydata.map(({ team }, index) => $('<li>').append([
$('<img>', { src: team.crestUrl }),
$('<a>', { id: 'to_details', href: '#' }).append($('<span>', {
id: index,
class: 'ui',
text: team.name
}))
])))
ul { list-style: none; margin: 0; padding: 0; }
li { display: flex; margin: 1rem 0; align-items: center; }
li img { margin-right: 1rem; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="data"></ul>
Upvotes: 3