broadband
broadband

Reputation: 3498

jQuery click event on $(this)

This is my testcase:

<!DOCTYPE html>
<html>
  <head>
    <script src="http://code.jquery.com/jquery-2.0.2.js"></script>
    <script type="text/javascript">

    $(document).ready(function()
    {
      $('.sequence').on('click', function()
      {
        e = $(this).next(); // div element, DOM element
        e.html(Math.random());

        e.on('click', function()
        {       
          e.html(Math.random());
        });

      });
    });
    </script>
  </head>
  <body>

    <div class="sequence">Sequence 1</div>
    <div>1</div>

    <div class="sequence">Sequence 2</div>
    <div>2</div>

  </body>
</html>

Upper code can be tested on http://jsfiddle.net/3LrXZ.

When I click on div Sequence 1, next div which first has text '1' gets some random value let us say 0.3126203578431159. Then I click on div Sequence 2 and next div which initially has value '2' gets some random value let us say 0.16280379495583475. Till now everything works as it should. Now when I click on the first 0.3126203578431159 the second div 0.16280379495583475 changes value. Element 0.312620357843115 should change value (get new random, not the second one).

Does this mean that you can not bind events on DOM element, that you can only bind events on html element id, class, some other attribute? Does't each DOM element has also some ID, which can be used.

Upvotes: 0

Views: 106

Answers (2)

z1m.in
z1m.in

Reputation: 1661

  var e = $(this).next(); // div element, DOM element
      e.html(Math.random());          

      e.on('click', function ()
      {
          $(this).html(Math.random());
      });

http://jsfiddle.net/59HgA/

Upvotes: 1

Fabr&#237;cio Matt&#233;
Fabr&#237;cio Matt&#233;

Reputation: 70209

Scoping issue. Your undeclared e becomes a global that is shared between both handlers. To fix it:

var e = $(this).next();

This will have an unique e inside each sequence' handler.

Demo

Upvotes: 7

Related Questions