Vitalii Plodistov
Vitalii Plodistov

Reputation: 125

Scope in jQuery(javascript)

I simplified my code for next example. So, please don't be wondered why I'm using ajax here.

 <!DOCTYPE>
<head>
     <style>.not { background:yellow; }</style>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>
    $(document).ready(function() {
        $(".not").click(function(e){
            e.stopPropagation();
            alert('good');
        });
        $(".click").click(function(e){
            $.post('page2.php', 'q=1', function(data){
                $('body').append('<p class="click">Click here to add new paragraph <span class="not">[not here]</span></p>');
            }, "json");
        });
    });
    </script>
</head>
<body>
    <p class="click">Click here to add new paragraph <span class="not">[not here]</span></p>
</body>

New rows don't make any alert for class=not! It is inexplicably for me :'(

Thanks for unswer!

Upvotes: 0

Views: 279

Answers (3)

bfavaretto
bfavaretto

Reputation: 71908

Assuming jQuery 1.7.x, use this:

$(document).on('click', ".not", function(e){
   alert('good');
}).on('click', ".click", function(e){
   if(!$(e.target).is('.not')) {
      $('body').append('<p class="click">Click here to add new paragraph <span class="not">[not here]</span></p>');
   }
});

The problem is, .click will only bind to elements that exist when it's called. Using .on the way I'm suggesting delegates the click handling to the document element. By passing a selector as the second argument, you tell jQuery to run the event handler only if the event target matches the selector.

Upvotes: 6

Dan Davies Brackett
Dan Davies Brackett

Reputation: 10071

In your ready event handler, you use $('.not).click. click is an alias for bind, and bind only works on elements that are already in the DOM.

If you're using jQuery 1.7, you can use on instead, in its delegate-like form.

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324610

Put the $(".not")... part inside a function, such as disableNot = function() {$(".not").click......}. Then, after appending the new paragraph, call disableNot() to update the event handlers. (Also call disableNot immediately after defining it, so any .not elements already on the page are given their handlers.)

Upvotes: 1

Related Questions