I'm working with a simple script to move an img object between two divs when it is clicked:
$('img').click(function()
{
if ($(this).parents('#div1'))
{
//alert('in gallery');
$(this).appendTo($('#div2'));
}
else if ($(this).parents('#div2'))
{
$(this).appendTo($('#div1'));
}
})
The开发者_Go百科 issue is that once the img is appended to div2, clicking on the img again won't move it back to div1. When I insert some test alerts, it looks like jquery still thinks the img is inside of div1.
Inspecting the element in the browser shows the img under div2.
Div2 is fixed to the bottom of the screen, while div1 is floated on the page. Is there anything that I'm not taking into consideration to make this work?
(first post here on SO, so please be gentle, happy to provide more info to help!)
thx!
The problem is with this: if ($(this).parents('#div1'))
It's not actually checking whether the img
is within #div1
, because jQuery always returns an object (containing an empty array) even if nothing is found. Since objects are "truthy" (i.e. {} == true
}, it will always go into the first if
block.
Change to:
if ($(this).parents('#div1').length)
to check if the parent exists.
精彩评论