javascript - Why does this jquery each() loop doesn't operate on unique classes -
i'm trying make jquery function work on classes unique identifier.. seems isn't adding var element... how do this
my code this...
var x = 1; $('.newest_posts').each(function() { $('.showfull' + x).on('click', function(e) { $('.newest_small' + x).hide(); // hide image preview on delete click $('.newest_full' + x).show(); // hide image delete link on click e.preventdefault(); }); x = x + 1; });
not versed in jquery i'm stumbled because have code works hiding them first
var = 1; $('.newest_posts').each(function() { $('.newest_full' + i).hide(); = + 1; });
you have ask question: x
equal when click handler called? not equal x
value when registered handler, equal value of x
after loop has completed.
assuming nothing else modified it, equal $(.newestposts).length() + 2
.
here quick fix problem:
var x = 1; $('.newest_posts').each(function() { var xcopy = x; $('.showfull' + xcopy).on('click', function(e) { $('.newest_small' + xcopy).hide(); // hide image preview on delete click $('.newest_full' + xcopy).show(); // hide image delete link on click e.preventdefault(); }); x = x + 1; });
it creates new variable inside scope of handling function.
an better fix dispense outer x
, use first parameter of each
handler, index.
$('.newest_posts').each(function(index) { var x = index + 1; $('.showfull' + x).on('click', function(e) { $('.newest_small' + x).hide(); // hide image preview on delete click $('.newest_full' + x).show(); // hide image delete link on click e.preventdefault(); }); });
Comments
Post a Comment