Saturday 15 June 2013

javascript - Can't Use :not() Selector -



javascript - Can't Use :not() Selector -

i trying create tic-tac-toe game , working on aspect of selecting boxes themselves, while using jquery :not selector doesn't seem working.

class="snippet-code-js lang-js prettyprint-override">function main(){ //functions $('.cell:not(.block)').click(function(){ $(this).addclass(color); $(this).addclass('block'); if(color=='g'){color='r';}else{color='g';} }); //variables var color = 'g'; } $().ready(main); class="snippet-code-css lang-css prettyprint-override">html { background-color:black; color:white; text-align:center; } .cell { border: 1px solid white; margin:1px; width:30%;height:30%; } .g {background-color:lime;} .r {background-color:red;} #board {height:500px;} class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <header>tic tac toe</header> <div id='board'> <div class='cell'></div> <div class='cell'></div> <div class='cell'></div> </div>

that isn't how jquery selects elements.

when run $('selector'), selector evaluated immediately, against current state of dom. 3 elements found because none of them have .block, , click handlers bound 3 elements.

there several ways of fixing this:

if want selector dynamically evaluated, need utilize on delegate event 1 of containing elements. event on specific kid element bubble containing element's handler , tested each time against selector. expensive option, , to the lowest degree desirable; shouldn't relying on jquery selectors kind of logic:

$('.board').on('click', '.cell:not(.block)', function () { // ... });

alternatively, simplest , cheapest alternative check .block in click handler:

$('.cell').click(function () { if ($(this).hasclass('block')) return; //...

finally, can unbind click handler @ same time add together .block class

$('.cell').click(function () { $(this).unbind( "click" ); // ...

javascript jquery html css

No comments:

Post a Comment