I'm using this code to display an alert on a certain element:
$("#resultsBox").click(function (event) {
console.log('a');
});
I want to display an alert only when you click on 'li' elements inside '#resultsBox'.
I'm trying to do it like this:
$("#resultsBox li").click(function (event) {
console.log('a');
});
This is the element's #resultsBox structure:
<div id="resultsBox">
<ul>
<li></li>
<li></li>
</ul>
</div>
How can this be done?
When you bind an event handler with .click()
it applies to any elements that matched your selector at that moment, not to elements later added dynamically.
Given your div is called "resultsBox", it seems reasonable to assume you are actually adding things to it dynamically to display the results of some other operation, in which case you need to use a delegated event handler:
$("#resultsBox").on("click", "li", function (event) {
console.log('a');
});
This syntax of the .on()
method binds a handler to "#resultsBox", but then when the click occurs jQuery checks whether it was on a child element that matches the "li" selector in the second parameter - if so it calls your function, otherwise not.
Something like this should work
$("#resultsBox").find("li").click(function(){
alert("You clicked on li " + $(this).text());
});
This should work now: http://jsbin.com/ocejar/2/edit
But anyway, also your example above using $("#resultsBox li")
should work just fine. See here. However, using $("#resultsBox").find("li")
should be a little faster in terms of performances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With