Reputation: 3607
I'm trying to iterate over li's in a ul using the jquery .each() method but the click function is not being initiated.
Basic HTML
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="product-list">
<ul class="list-inline">
</ul>
</div>
</div>
</div>
Which is populated on pageload with the following jquery function
JQUERY
productLoad: function() {
for (var i = 0; i < state.greens.length; i++) {
$(".product-list ul").append("<li><div class='product'><p> " + state.greens[i].name + " </p></div></li>");
}
},
productLoad is part of a larger object called display and is initiated by display.productLoad();
I'd trying to write a function that calls another function called display.arrange(arg) which causes the page to display a lot of information about the corresponding object in state.greens.
I'm trying to use jquery's .each method in the following way:
JQuery
$(".product-list > li").each(function(index) {
$(this).click(function() {
display.arrange(index);
})
});
The idea is that I add an li for each object in state.greens with productLoad, and then use .each to initiate a function that references each li's corresponding place in state.greens to display information about it.
However, when I click on the li's nothing happens at all, and there are no error messages in the console that correspond to that function so I don't think the click handler is being called.
You can see a working example of what I have on this page: Click to go to page
Scroll down to where it says "Click On A Product To Go To Its Detail Page" and you'll see the ul with each of the stylized li's that represent each product in state.greens.
Upvotes: 1
Views: 58
Reputation: 6467
Reviewing your HTML
code, your CSS selector is wrong. Consider that >
is used for get immediate children, then your CSS should start selecting the UL
tag in order to get all its LI
children
Change:
$(".product-list > li")....
By:
$("ul.list-inline > li")...
Upvotes: 1
Reputation: 697
I believe this is because you're creating (ie, appending) your <li>
s using jQuery. That is, they're not in your initial DOM when the page loads. So you need to use jQuery's ".on" to delegate the click event. I'm also not sure that I fully understand what you're trying to accomplish, but I don't think that needs to be in an .each
...you should be able to do the following and just use this
:
Try switching out your jQuery from this:
$(".product-list > li").each(function(index) {
$(this).click(function() {
display.arrange(index);
})
});
to this:
$(".product-list").on("click", "li", function(index) {
// Run functions, mo' jQuery, etc.
});
That should get your click to register. From there, what you run inside the .on("click")
is up to you.
Upvotes: 1
Reputation: 3039
Try this:
$(".list-inline").on("click", ">li", function(){
display.arrange($(this).index());
});
Upvotes: 2