我想创建一个图像元素并使用 jQuery 将其分配/包装在一个类中。图像还必须充当链接,即当用户单击它时,应打开指定的网站。以下示例代码创建了一个指向 Google 网站的图像元素。如何将此元素分配给指定的类?
$('<img />').attr({'src':src})
.appendTo($('<a />').attr({href:'http://www.google.com'}).appendTo($('#targetLocation')));
var img = $('<img />', {src:src, 'class':'imgClass'}),
anchor = $('<a />' , {href:'http://www.google.com'}),
div = $('<div />', {'class':'myClass'});
div.append( anchor.append(img) ).appendTo( $('#targetLocation') );
最终得到
<div id="targetLocation">
<div class="myClass">
<a href="http://www.google.com">
<img src="whatever" class="imgClass" />
<a/>
</div>
</div>
而且您以正确的方式进行操作,当您可以使用实际的真实对象时,您不应该使用字符串。
为什么不直接创建并附加一个变量?
var imgElement = "<a href='www.yourlink'><img class="your class" src="your src"/></a>";
$("#targetLocation").append(imgElement);
只需将所有 html 构建为字符串并调用
var theHtmlString =
"<a href="http://google">" +
" <img src="whatever"></img>" +
"</a>";
$('#targetLocation').append(theHtmlString);
虽然这也会将此 HTML 添加到目标位置元素中的内容中,但您可能希望替换该元素:
$('#targetLocation').html(theHtmlString);