Reputation: 599
A newbie question, I obtain a var from a json through a cicle like this
$.each(json.Links,function(i,link)
I will then append that variable to content using this
$('#content').append('<br>').append(link);
This works, but I also would wish to add to the link an href so that when a user clicks on the link he will be direct to another page but I don't know how to do this
Edit: Full html and script js
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="script.js"></script>
<title>Fake Delicious</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
</head>
<body>
<header>
<!-- Inserir banner -->
<h1>Delicious Testing Page</h1>
</header>
<div id="content">
coisa
</div>
</body>
</html>
Script
var url="printTables.php?option=6";
$.getJSON(url,function(json)
{
$.each(json.Links,function(i,link)
{ var test="test"+i;
var but=$("<button>Show info</button>");
$(link).attr("href", link);
$('#content').append('<br>').append(link).append($('<div>').append(but));
});
})
The button at this stage isn't suposed to do anything. The link as I said it's correct since the html shows it properly I just now want to add an hyperlink to it for another page
Upvotes: 1
Views: 6828
Reputation: 83356
If you have a variable with a string in it, representing an anchor tag, wrap it with the jQuery function, then save that result. That will give you an actual tag that you can manipulate with jQuery further.
Then use the attr function to set its href
. These steps can be combined.
This works for me:
var linkFromJson = "<a>Hello</a>";
linkFromJson = $(linkFromJson).attr("href", "http://www.google.com");
$("#main").append(linkFromJson);
So for your example, change this:
$(link).attr("href", link);
to this:
link = $(link).attr("href", link);
Upvotes: 1