jQuery:用A锚标记包装图像标签的最简单方法 [英] jQuery: Easiest way to wrap an image tag with an A anchor tag
问题描述
这是我的问题的简化版本。
This is a simplified version of my problem.
我有两个按钮和一个图片。图片代码如下所示
I have two buttons, and one image. The image code is something like this
<img class="onoff" src="image.jpg">
当我按下按钮我想要的图像包裹在一个A标签,如
When I press button one I want the image to be wrapped in an A tag, like
<a href="link.html">
<img class="onoff" src="image.jpg">
</a>
当我按另一个按钮时,A标签应该被删除。
And when I press the other button, the A tags should be removed.
使用jQuery最简单的方法是什么?
What's the easiest way of doing this with jQuery?
推荐答案
你已经有很多答案,但(至少在我开始写作之前)没有一个会正确工作。
you have already many answers, but (at least before I started writing) none of them will correctly work.
他们不考虑你应该不用多个< a>
标签包装< img>
。此外,不要尝试解开它,如果它不包裹!
They do not take into account that you should not wrap the <img>
with multiple <a>
tags. Furthermore, do not try to unwrap it if it is not wrapped! You would destroy your DOM.
此代码简单在包装或解开之前进行验证:
This code simple does a verification before wrapping or unwrapping:
$(function(){
var wrapped = false;
var original = $(".onoff");
$("#button1").click(function(){
if (!wrapped) {
wrapped = true;
$(".onoff").wrap("<a href=\"link.html\"></a>");
}
});
$("#button2").click(function(){
if (wrapped) {
wrapped = false;
$(".onoff").parent().replaceWith(original);
}
});
});
祝你好运!
这篇关于jQuery:用A锚标记包装图像标签的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!