Skip to content Skip to sidebar Skip to footer

Jquery: Check If An Element Is Assigned To A Var

I'm trying to create a simple button manager to select and eventually unselect allready checked img elements which contains CSS class .my_class, why this doesn't work? var last_sel

Solution 1:

It doesn't work because each time you call $(this) a new jQuery wrapper object is created.

Instead, try just saving "this":

var last_selected;
$("img.my_class").click ( function () {
  if (last_selected != null) alert (this === last_selected);
  last_selected =  this;
});

Solution 2:

why not assign a 'selected' class to the currently selected img?

$('img.my_class').click(function()
{
    // remove the selected class from the previous selected
    $('img.my_class.selected').removeClass('selected');
    // flag the current one as selected
    $(this).addClass('selected');
});

Solution 3:

Each time you wrap this you create a new jQuery object. Two jQuery objects are not equal to each other just because they wrap the same element ($(this) != $(this)).

Instead, assign this itself to last_selected and everything should work as expected.

var last_selected;
$("img.my_class").click ( function () {
    if (last_selected != null) alert (this == last_selected);
    last_selected = this;
});

Post a Comment for "Jquery: Check If An Element Is Assigned To A Var"