Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery on method not working

Tags:

jquery

I am trying to use jquery on method on 1.7.2 but I am having trouble.

I am using this

$(function(){
$("a").on("click",'.displayBig', function(e) {
    e.preventDefault();
    alert('foo');
})});
<a href="images/large_4.jpg" class="displayBig" data="gallery0"><div id="magnify">dsfsfdsfs</div></a>​

​ It seems that my selector is not working.

I have created a jsfiddle here.

http://jsfiddle.net/BQDvM/

Thanks Guys.

like image 739
Tom Avatar asked Dec 28 '22 02:12

Tom


1 Answers

If you want to use the dynamic version of .on(), then you need to use this form:

$(staticParentSelector).on('click', '.displayBig', fn);

The staticParentSelector must be a selector that points to a parent of your dynamic objects and is present at the time you run the above jQuery to install the event handlers and it must be an object that is not destroyed and recreated after the event handlers are installed. The objects that match the second selector (I'll call the dynamic selector) do not need to exist initially and can be created any time in the future.

In the worst case, it could be this:

$(document).on('click', '.displayBig', fn);

Since the document object satisfies all the criteria for a static parent. But, your events will perform better if you pick a static parent that is much closer to your actual dynamic objects and if you do not use the document object for all dynamic events.

So, if you had HTML like this:

<div id="container">
    <a href="images/large_4.jpg" class="displayBig" data="gallery0">
        <div id="magnify">dsfsfdsfs</div>
    </a>
</div>

Then, you would use a dynamic version of .on() like this:

$("#container").on('click', '.displayBig', fn);

The way the dynamic version of .on() works is that it binds a single event handler to the static object. Then, when someone clicks on one of your dynamic objects, there are no direct event handlers on the object for the click so the click bubbles up through the ancestor objects. When the event gets to your staticParent object that has the event handler, it sees that there is a dynamic event handler installed and it compares the object that originated the event to the dynamic selector. If they match, it fires the event handler. If they don't match, no event is fired.

like image 101
jfriend00 Avatar answered Jan 08 '23 00:01

jfriend00