Jquery, add & remove element on hover

我只是一个虾纸丫 提交于 2019-12-22 10:37:49

问题


I came a cross a problem which I tried pretty much everything without a solution.

$('a.hovered').hover(function () {
    $(this).after(' <img src="images/icons/famfamfam/silk/user_go.png" />');
},function () {
    $(this).remove(' <img src="images/icons/famfamfam/silk/user_go.png" />');
});

Of course I tried many versions of this remove() without any success. I will be glad if anyone could help me out with this problem.

Additionally I would like to add effect of fadeIn() and fadeOut() but of course this wasn't successful also.

I can add the image but I can't remove it (even fadeIn didn't work while I can successfully add images).

Thank you for your help and time in advance.


回答1:


You really don't want to do that. Your code will be quicker, clearer and easier to maintain if you just show and hide an image that always exist.

Just put the img into your html with and id set and style="display: none;" to hide it.

Your javascript code then becomes:

$('a.hovered').hover(function () {
    $("#user_go").show();
},function () {
    $("#user_go").hide();
});



回答2:


Name you elements, it'll make life easier for you, i.e.:

$('a.hovered').hover(function () {
    $(this).after(' <img id="user_go" src="images/icons/famfamfam/silk/user_go.png" />');
},function () {
    $("#user_go").remove();
});



回答3:


You cant reference to created object in such manner, try

$('a.hovered').hover(function () {
    $(this).after(' <img src="images/icons/famfamfam/silk/user_go.png" id="addedImage"/>');},
    $('#addedImage').remove();
});

Yep, and while I write, two other post the same stuff :)




回答4:


.remove() doesn't take a piece of HTML:

$('a.hovered').hover(function () {
    $(this).after(' <img src="images/icons/famfamfam/silk/user_go.png" id="go_image" />');
},function () {
    $('#go_image').remove();
});



回答5:


why not just do this?

$('a.hovered').hover(function () {      
$(this).after(' <img src="images/icons/famfamfam/silk/user_go.png" />');  },
function () {
$(this).find('img').remove();
 });  


来源:https://stackoverflow.com/questions/5497866/jquery-add-remove-element-on-hover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!