How do I refer to an appended item in jQuery?

北城以北 提交于 2019-12-11 02:04:05

问题


I want to create and append an item in jquery, while saving a reference to it.

 var buy = "<img src='img/buy-now.png' />";      
 var $buy = $(buy).appendTo("body");
 $buy.html("hello");

I was expecting something like the above to work. Any ideas?


回答1:


In short, $buy is the object you've appended, you're just doing an invalid operation. <img /> is a self-closing tag, there is no HTML inside it, so .html("something") will have no effect.

If you meant to set the tooltip, use .attr(), like this:

$buy.attr('alt', 'hello');



回答2:


Yes, the variable $buy will save the reference of the element and the jQuery object.

Edit: $buy.html("hello"); will add "hello" inside the image tag, however it will be hidden on the screen since the image is being displayed.



来源:https://stackoverflow.com/questions/3122125/how-do-i-refer-to-an-appended-item-in-jquery

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