-5
<ul>
    <li id="one"></li>
    <li id="two"></li>
    <li id="three"></li>
    <li id="four"></li>
    <li id="five"></li>
    <li id="six"></li>
    <li id="seven"></li>
    <li id="eight"></li>
</ul>

Script

$.getJSON("data.php", function(data) {
    var items = [];
    $.each(data, function(i, val) {
        $("#" + i).html("<a href='javascript:void(0);' class='hov'>" + val + "</a>");
    });
});
$('.hov').click(function() {
    alert("Handler for .click() called.");
});

data.php is :

{
    "one": "yahoo",
    "two": "gooogl",
    "three": "bing",
    "four": "ebay",
    "five": "ask",
    "six": "gmail",
    "seven": "alexa",
    "eight": "example",
    "nine": "ymail"
}
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
user1650455
  • 1
  • 1
  • 4

1 Answers1

2

You need to bind the click handler after the element is loaded,

$.getJSON("data.php", function(data) {
    var items = [];
    $.each(data, function(i, val) {
        $("#" + i).html("<a href='javascript:void(0);' class='hov'>" + val + "</a>");
    });
    $('.hov').click(function() {
        alert("Handler for .click() called.");
    });
});

Other option is to use delegates. Then your code will be like,

$.getJSON("data.php", function(data) {
    var items = [];
    $.each(data, function(i, val) {
        $("#" + i).html("<a href='javascript:void(0);' class='hov'>" + val + "</a>");
    });

});
$(document).on('click', '.hov', function() {
    alert("Handler for .click() called.");
});
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53