Reputation: 1867
I am generating a link dynamically using jQuery by iterating some Json data.
MyCode :
var content = "<table>";
$.each(dataArray, function( index, value )
{
content = content+"<tr><td>"+value.Version+"</td><td><a href="+value.Download+"> Download</a></td></tr>";
});
content = content+"</table>";
$('#tablediv').append(content);
It should generate a table with a link in 2nd colum as:
< a href="link to url"> Download < /a>
But it generates it as :
< a href="link to url">< /a> Download
So I need text between start and end tag but it appears after end tag. How to resolve this issue?
Upvotes: 0
Views: 47
Reputation: 225
$(document).ready(function(){
var content = "<table>";
var dataArray=[{Version:1,Download:"asdsa"},{Version:2,Download:"tete"}];
$.each(dataArray, function( index, value )
{
var $row=$("<tr>");
var $rowcellVersion= $("<td>").text(value.Version);
var $rowcellContent= $("<td>");
var $anchorTag = $("<a>").text("Download")
.attr("href",value.Download)
.appendTo($rowcellContent);
$rowcellVersion.appendTo($row);
$rowcellContent.appendTo($row);
content = content + $row[0].outerHTML;
});
content = content+"</table>";
$('#tablediv').append(content);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="tablediv"></div>
A bit cleaner way of handling the creation of elements .Also you can check the HTML in page inspector .It's the expected way
Upvotes: 1
Reputation: 2957
You can leverage jQuery if you are using it in a first place
var content = $("<table>");
$.each(dataArray, function( index, value )
{
content.append($("<tr />")
.append($("<td />").text(value.Version))
.append($("<td />").append(
$("<a />").attr("href",value.Download).text(value.Version))
);
$('#tablediv').append(content);
Upvotes: 0
Reputation: 1650
You need to add single-quotes to your href attribute.
content += "<tr><td>"+value.Version+"</td><td><a href='"+value.Download+"'> Download</a></td></tr>";
Upvotes: 2
Reputation: 20260
You need to wrap value.Download
in quotes:
"... <a href=\"" + value.Download + "\">Download</a> ...";
Upvotes: 1