jquery click() event won't work for appended h

2020-04-17 06:16发布

问题:

There are a couple of things I need to explain before my question makes sense. On my first page I have a main div where I'm loading markup from another page using the jquery load() method. The html I'm loading is linked to a .js page where my script is. The js page is where I'm manipulating the content of the main div. On my js page I loop through an array of variables I pull from a database and append() them to the main div. In the for loop I wrap each row in its own div and include an anchor tag. The anchor tag is what I want to attach the click() method to so I can call a function once it is clicked. I've tried the parent > child selector among others, but nothing works for the anchor tag. My code:

//this is the query to my parse database

query.find({
  success: function(results) {
    for (i = 0; i < results.length; i++){

        activity = results[i].get("activity");
        scene = results[i].get("location");
        neighborhood = results[i].get("neighborhood");
        date = results[i].get("date");
        details = results[i].get("details");
        time = results[i].get("time");
        search.push([activity, scene, neighborhood, date, details, time]);

        for (i = 0; i < search.length; i++) {

            //append each row of results to mainDiv inside of their own div with an anchor tag at the end of each row.
            //when the anchor tag is clicked I want to call a function, but none of the selectors I've tried have worked. 

            $('#mainDiv').append("<div id='event'>" + search[i].join(' ') + "<a href='#' id='interested'>Interested?</a></div>");
        }

    };// closes for loop
    },//closes success function
  error: function(error) {
    alert("Error: " + error.code + " " + error.message);
  }
}); //closes find

回答1:

I found an answer here: Newly appended div doesn't inherit event handler in document ready

The shortcut event handlers (such as click(), mouseover() etc) will only apply to elements which are available to the DOM on page load. When appending elements dynamically you have to attach the event to a static parent element, and supply a filter which you wish to delegate events to, like this:

This was my solution:

$("#mainDiv").on('click', '.interested', function(){
       alert("working");
   });