Insecure .on () method

I used the method $.click()to trigger some events. But then I needed to set some events for some HTML elements before the elements were declared. Take this as an example:

<script>
    $('div.hide').click(function() {
        $('div.hide').css({'display' : 'none'});
     });
</script>
<div class="hide">some text</div>

The disadvantage is that when you configure the method, the .click()elements div.hidedo not exist, so the trigger is not installed.

So, I turned to the method .on(), for example:

<script>
    $('div.hide').on('click', function() {
        $('div.hide').css({'display' : 'none'});
    });
</script>
<div class="hide">some text</div>

But that doesn't work either. I thought the call .on()would make all existing and future elements div.hiderun 'click' function().

I managed to overcome this inconvenience, but for my own knowledge I would like to know what I was doing wrong. Can't assign a trigger to future HTML elements?

My friend was:

<script>
    $(document).ready( function() {
        $('div.hide').click(function() {
            $('div.hide').css({'display' : 'none'});
        });
    });
</script>
<div class="hide">some text</div>
+5
2

:

$('body').on('click', 'div.hide', function() { ... });

<body>, , , ( ).

<body>; <div>.

"on" "live" "delegate", "bind".

+10
-2

All Articles