NoahLE
NoahLE

Reputation: 325

jQuery getting .preventDefault() to work on generated elements

I'm having a bit of a problem with getting the .preventDefault to work on some elements I am generating via JQuery.

I am getting a JSON file using the following code and putting the data into individual p elements:

$.getJSON(searchURL, function(data) {
        $.each(data, function(key, value) {
            if (typeof value === 'object') {
                for (var i = 0; i < data.count; i++) {
                    var fullPlayerURL = "<p class='entry'>" + "<a href=" + playerURL + data.data[i].id + ">"
                        + "Nickname - " + data.data[i].nickname + "</a>" + "</p>"
                    $('#results').append(fullPlayerURL);
                }
            }
        });
}); //end getJSON

Then I'm using the following code to stop the link from redirecting when clicked (links to another JSON file):

$('.entry').click(function(event) {
    event.preventDefault();
    var linkClicked = $(this).attr("href");
    console.log(linkClicked);
});

I don't know if it matters but #results is just an empty div.

Here's all the code if this isn't enough info (sorry it's such a mess).

Upvotes: 0

Views: 453

Answers (2)

su-ex
su-ex

Reputation: 106

Sorry, I'm not allowed to comment on adeneo's answer. For me var linkClicked = $('a', this).attr("href"); gives undefined. I had to make var linkClicked = $(this).attr("href"); out of it.

Edit: Know it, I wanted to address the anchor.

$('#results').on('click', 'a', function(event) {
    event.preventDefault();
    var linkClicked = $(this).attr("href");
    console.log(linkClicked);
});

Upvotes: 0

adeneo
adeneo

Reputation: 318222

You'll need delegated event handlers for dynamic elements

$('#results').on('click', '.entry', function(event){
    event.preventDefault();
    var linkClicked = $('a', this).attr("href");
    console.log(linkClicked);
});

Upvotes: 5

Related Questions