views:

35

answers:

4

Hi, 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_selected;
$("img.my_class").click ( function () {
    if (last_selected != null) alert ($(this) == last_selected); // returns false everytime
    last_selected =  $(this);
});
+1  A: 

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;
});
Pointy
+1  A: 

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');
});
DoXicK
A: 

Calling $(this) creates a new jQuery object. You can't compare it with a jQuery object previously returned by $(this) and expect them to be equal. You can't compare two objects by value either:

>>> a = {foo: 42};
Object { foo=42}

>>> b = {foo: 42};
Object { foo=42}

>>> a === b
false

>>> a == b
false
Frédéric Hamidi
That's true, but elements from the DOM are comparable.
Pointy
@Pointy, you're right, I tried to clarify my answer.
Frédéric Hamidi
A: 

Each time you wrap this you create a new jQuery object. Two jQuery objects are not equal to each 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;
});
Alex Barrett
should probably use `===` in the comparison.
Pointy
It works, thanks for help
Vittorio Vittori