My Json format is as follows:
[{"id":"1","Text":"esj","DateTime":"2015-10-21 19:00:00", "Color":"Red"},
{"id":"1","Text":"esj","DateTime":"2015-10-21 19:00:00", "Color":"Red"},
{"id":"1","Text":"esj","DateTime":"2015-10-21 19:00:00", "Color":"Red"},
{"id":"1","Text":"esj","DateTime":"2015-10-21 19:00:00", "Color":"Red"}]
I also have a jquery script in which I'm adding dinamically hyperlinks:
$.ajax({
url: './download.php',
type: "POST",
data: {
id: id
},
dataType:'text',
success: function(ans)
{
var data = JSON.parse(ans);
$.each(data, function(i, v) {
$('links').append('<li><a><div>' + v.Text + '<span class="small">' + v.DateTime+ '</span></div></a></li>');
});
}});
I want a simple effect - a list of hyperlinks on my webpage. When user cliks any hyperlink, he will see an alert window with the value of the field id, Color, DateTime and Text.
I tried adding a function inside $.each:
$.find('a').click(function(){
alert(v.Color+v.id+v.Date+v.Text);
})
But it tells me:
Uncaught TypeError: $.find(...).click is not a function
So how can I append a function (click handler) to each generated link that will be displaying all properties related to the clicked link?
There is two problems here:
$.find('a') is not going to work. You need to select a dom element first on which you will apply the selector (e.g. $(document).find('a')).lis to an element selected using $('links'). This is not going to work either. This syntaxe selects tag. There is no HTML tags <links>. I guess what you are actually trying to do is to select the dom element with the id "links". To do so you need to do $('#links').Here is a working snippet.
var data = [
{"id":"1","Text":"esj","DateTime":"2015-10-21 19:00:00", "Color":"Red"},
{"id":"1","Text":"esj","DateTime":"2015-10-21 19:00:00", "Color":"Red"},
{"id":"1","Text":"esj","DateTime":"2015-10-21 19:00:00", "Color":"Red"},
{"id":"1","Text":"esj","DateTime":"2015-10-21 19:00:00", "Color":"Red"}
];
$.each(data, function(i, v) {
// Create the li.
var li = $('<li><a href="#"><div>' + v.Text + '<span class="small">' + v.DateTime + '</span></div></a></li>');
// Append it to the dom element with the id "links".
$('#links').append(li);
// Attach the click handler to its <a> child.
var a = li.find('a').on('click', function(e){
e.preventDefault();
alert(v.Color + " " + v.id + " " + v.DateTime + " " + v.Text);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="links"></div>
Try on:
$('#links').on('click', 'a', function() {
alert('message');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With