如何使用 jQuery .append() 附加图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16432001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append image using jQuery .append()?
提问by yvonnezoe
I could append a string to my table to show the status as such
我可以在我的表中附加一个字符串来显示状态
$('#test').empty().append("on")
but it would be better if i can display an image instead of a string. i tried this:
但如果我可以显示图像而不是字符串会更好。我试过这个:
$('#test').empty().append(<img src="/static/on.png" height="64px" width="64px">)
but it's not working. How should i do it?
但它不起作用。我该怎么做?
回答by PSL
Missing quotes:
缺少报价:
$('#test').empty().append('<img src="/static/on.png" height="64px" width="64px">');
Since you are emptying and appending item. you could do this instead. .html
will replace the whole content of your selector with image item. Later on if you want to append to this div you can do .append(...);
由于您正在清空并附加项目。你可以这样做。.html
将用图像项替换选择器的全部内容。稍后如果你想附加到这个 div 你可以做.append(...);
$('#test').html('<img src="/static/on.png" height="64px" width="64px">');
If you are planning to empty
and append image then .html()
is the best approach for you.
如果您打算empty
并附加图像,那么.html()
这对您来说是最好的方法。
回答by Arun P Johny
Try
尝试
$('<img />', {
src: 'test.png',
width: '200px',
height: '100px'
}).appendTo($('#empty').empty())
回答by Elliot Bonneville
You need to surround the HTML to be appended with quotes:
您需要将要附加引号的 HTML 括起来:
$('#test').empty().append('<img src="/static/on.png" height="64px" width="64px">');
I used single quotes here because you already have double quotes in the HTML, so they would escape the string if you used doubles to surround it.
我在这里使用单引号是因为您在 HTML 中已经有双引号,所以如果您使用双引号将它括起来,它们会转义字符串。