开发者

How to refresh jQuery Selector Value after an 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 'selectee' class to all div which has 'chess_piece' class then I select DIVs 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 type of DIV element with class named 'chess_square selectee' and 'chess_square' which d开发者_开发技巧oesn't meant to be clickable. I move around Sub DIV of 'rps_square selectee' from DIV2 to DIV1 and add and remove classes to be exactly same like this. The meaning is Queen Piece is moved 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 jQuery doesn't update var $selectee = $('.rps_square.selectee');. Even though I changed class names, DIV1 is not clickable and DIV2 is still clickable. By the way, I've used jQuery UI selectable but doesn't refresh either.


Instead of .bind(), use .live() like this:

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

It's not that jQuery isn't updating the collection, though it isn't. It's that you already bound the event handler to the matching DOM elements.

Using .live() listens at the DOM root for the click and executes if it matches the selector...if the class changed, it'll no longer match the selector, and the handler won't execute, which is what you're after. The reverse is true as well, if anything new matches the selector, when it's click bubbles the handler will execute for it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜