Reputation: 145
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
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