javascript - jquery $.each incorrect binding? -
<div id='a'>a</div> <div id='b'>b</div> <div id='c'>c</div> <div id='d'>d</div>
this javascript:
var first = [$('#a'), $('#b')]; var second = [$('#c'), $('#d')] var = [first, second]; (var i=0; i<everything.length; ++i) { var current = []; (var j=0; j<everything[i].length; ++j) { current.push(everything[i][j]); } $.each(current, function(i,d) { d.hover(function() { $(current).each(function() { this.css('background-color', '#00ff00') }); }, function() { // hover out $(current).each(function() { this.css('background-color', 'white') }); }); }); }
this code little strange because took original code nerf down presentable here.
why c,d highlighted when hover on a,b?
fiddle: http://jsfiddle.net/c4rsj/4/
edit
desired behavior: a,b highlight when hover on or b , c,d highlight when hover on c or d
it’s because current
holds references #c
, #d
when hover handler function executed.
use variable inside of each loop create scope preserves current value, this:
$.each(current, function (i, d) { var _cur = current; // local variable preserve value of current within scope of function d.hover(function () { $(_cur).each(function () { this.css('background-color', '#00ff00') }); }, function () { // hover out $(_cur).each(function () { this.css('background-color', 'white') }); }); });
Comments
Post a Comment