How do I update the jQuery selector value after execution?

$ (document) .ready (function () {

var $clickable_pieces = $('.chess_piece').parent();
$($clickable_pieces).addClass('selectee'); // add selectee class

var $selectee = $('.chess_square.selectee');

// wait for click 
$($selectee).bind('click',function(){
    $('.chess_square.selected').removeClass('selected');
    $(this).addClass('selected');
    { ........... }

});

      

I initially inject a class 'selectee'

to all divs that have a class < chess_piece

', then I select a DIV with that class $('.chess_square.selectee')

.

<div id="clickable">
    <div id="div1" class="chess_square">
    </div>

    <div id="div2" class="chess_square selectee">
          <div id="sub1" class="chess_piece queen"></div>
    </div>

    <div id="div3" class="chess_square">
    </div>

</div>

      

There are two types of DIV with the class "chess_square selectee" and "chess_square", which are not intended to be clickable. I move the Sub DIV from "rps_square selectee" from DIV2 to DIV1 and add and remove classes just like this. The Queen Piece value moves from Div2 to Div1.

<div id="div1" class="chess_square selectee">
  <div id="sub1" class="chess_piece queen"></div>
</div>

<div id="div2" class="chess_square">
</div>

<div id="div3" class="chess_square">
</div>

      

However, the problem is that jQuery is not updating var $selectee = $('.rps_square.selectee');

. Even though I changed the class names, DIV1 is not clickable and DIV2 is still clickable. By the way, I used jQuery UI but am not updating.

+2


a source to share


1 answer


Instead, .bind()

use .live()

like this:

$('.chess_square.selectee').live('click',function(){
    $('.chess_square.selected').removeClass('selected');
    $(this).addClass('selected');
    { ........... }    
});

      



It's not that jQuery doesn't update the collection, although it doesn't. This is what you have already associated the event handler with the corresponding DOM elements.

With .live()

listens at the root of the DOM for click

and is executed if it matches the selector ... if the class is changed it will no longer match the selector and the handler won't execute, which is what you want. The converse is also true if something new matches the selector, when it click

bubbles, the handler will execute for it.

+8


a source







All Articles