What is the difference between the calling of jquery functions using on and after find using on
<div class="outer">
<span>One</span>
<div class="inner"><button id="button">button 1</button></div>
</div>
<div class="outer">
<span>Two</span>
<div class="inner"><button id="button">button 2</button></div>
</div>
The jquery code is
$(document).ready(function(){
$('div.outer').on('click',".inner #button",function(event){
console.log(this);//this works
});
$('div.outer').find(".inner #button").on("click",function(event){
console.log(this);//this works
});
$('div.outer').find(".outer span").on('click',function(event){
console.log(this);//this not works
});
});
Here it is a simple example I am creating a jquery plugin which has multiple instances so each button clicked twice. I used jquery.off before bind each function, but it not works.
The first one is a dynamic event handler, it binds the event to
div.outer, a parent of#button, but filters based on the#buttonselector, that way it works even if the element is not present at the time the event is bound, i.e. dynamically insterted elements.The two last ones are regular event handlers, and
find()just finds an element within another element, so in the middle one it searches for#buttonwithin.innerwithin.outer, and attaches a regular event handler to#button.As ID’s are unique, it’s really uneccssary to use find that way, as just
$('#button').on()should be enough.In the last one the click is bound to the span, and not the button, so any click on the button will not fire the event, but clicking on the span will.
EDIT:
Your selector searches for
.outerinside.outer, that’s why it’s not working, you should be searching for just a span inside .outer, so this:should be this:
FIDDLE