qb1234
qb1234

Reputation: 145

How can retrieve click data from dynamically created elements?

This code loop appends dynamically created li's to #carList

for (var i = 0; i < car.length; i++) {
                var carNow = car[i];

                $('#carList').append("<li>" + carNow.carName +
     </li>").data("item", {
                    index: i
                });

            };

This code binds a click eventListener to ul#carList. I know tht I must use the JQuery object ($(this)) to expose the data on the clicked li but I'm not sure exactly how..Any help is appreciated

 $('#carList').on('click', "li", one);

 function one() {
            controller.setCurrentCar($(this));
            carView.render();
        }

Upvotes: 0

Views: 31

Answers (2)

Jeric Cruz
Jeric Cruz

Reputation: 1909

You can add class to each <li> then put a click event on that class.

var car = [{
  carName:"Subaru",
  model:"X1"
}, 
{
  carName:"Alfa Romero",
  model:"car2"
}]

$(function(){
  for (var i = 0; i < car.length; i++) {
    var carNow = car[i];

    $('#carList').append("<li class='car-item'>" + carNow.carName +
      "</li>").data("item", {
      index: i
    });
  };
  //click event for class .car-item
  $(".car-item").click(function(e){
    alert($(this).text());
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Click on the car names:<br>
<ul id="carList"></ul>

Upvotes: 1

Musa
Musa

Reputation: 97672

You use the same .data() method you used to set the data to retrieve it using the same string you used to set it

$(this).data("item");

Upvotes: 0

Related Questions