1

I am adding list items w/ child anchor tags to a unordered list depending upon what is returned from an AJAX request. These exist inside of a drop down and require the unique text value returned for when each specific anchor is clicked. x is the unique value that each item is being created for in the script bellow.

var appendDropDwn = function appendDropDwn(x) {
        console.log("Append Drop Down");
        var html = "<li><a href='#' class='x-list' id="+ x + ">" + x + "</a></li>"
        console.log(html);

$("#x-dropdown-ul").append(html);
}

I then create an event listener using the class in the append function above,

    $(".x-list").click(function (e) {
        var y = $(this).text();
        alert(y);

    });

The issue is that when the anchor element is clicked, the script runs for all anchor tags. In other words if their is 100 list item/anchor tags appended to the UL in the first script, then the second script runs 100 times but only alerts the .text() of the one actually clicked. It alerts the same text value 100 times.

LCaraway
  • 1,065
  • 17
  • 36

2 Answers2

2

It sounds as if the click function is attached multiple times. If it is attached to all $(".x-list") elements, a second run would also append to previously created elements.

You could append the click directly to the created objects, or you could attach the function to the parent ul once (on DOM ready, outside the Ajax data handling, so the it is attached only once!) and use event.Target to determine which label was clicked

 $("#x-dropdown-ul").click(function (e) {
        var y = $(e.target).text();
        alert(y);
    });

(If needed you could further filter on .x-list , but since the li seems to contain only the tag, this would suffice? )

Me.Name
  • 11,334
  • 3
  • 25
  • 41
  • You nailed it. I was adding the listener when handling the AJAX. Moved it out as well as moved the filter up a level to the
      . This did the trick. Thanks!
    – LCaraway Jun 29 '16 at 16:07
1

I would modify the click event so it could better handle .x-list items that are created dynamically.

$("#x-dropdown-ul").on('click', '.x-list', function (e) {
    var y = $(this).text();
    alert(y);
});

Please see this post for more information:

Event binding on dynamically created elements?

Community
  • 1
  • 1
Ben Harrison
  • 1,771
  • 4
  • 19
  • 38