这是我的问题的一个简化版本。
我有两个按钮和一个图像。图像代码如下所示
<img class="onoff" src="image.jpg">
当我按下按钮一时,我希望图像被包装在一个A标签中,比如
<a href="link.html">
<img class="onoff" src="image.jpg">
</a>
当我按下另一个按钮时,A标签应该被移除。
用jQuery做这件事最简单的方法是什么?
发布于 2009-11-20 07:49:57
对元素进行换行
$(".onoff").wrap("<a href='link.html'></a>");
和解包
$(".onoff").parent().replaceWith($(".onoff"));
发布于 2009-11-20 07:48:49
尝试如下所示:
$("img.onoff").wrap(
$("<a/>").attr("href", "link.html"));
但也许在图像本身上使用jQuery的click
绑定要比将图像包装在锚点中要好。
发布于 2009-11-20 07:48:25
您可以使用jQuery wrap()函数。
代码是:
<input type="button" id="button1" value="Wrap" />
<input type="button" id="button2" value="Unwrap" />
<img class="onoff" src="image.jpg" alt="" />
$(function() {
//wrap
$('#button1').click(function() {
$('.onoff').wrap('<a href="link.html"></a>');
//if you want to make sure multiple clicks won't add new <a> around it
//you could unbind this event like that:
//$(this).unbind( "click" )
});
//unwrap
$('#button2').click(function() {
$('.onoff').parent().each(function() { $(this.childNodes).insertBefore(this); }).remove();
//$(this).unbind( "click" )
});
});
https://stackoverflow.com/questions/1767414
复制相似问题