replaceWith自动关闭标记 [英] replaceWith Automatically Closes the Tag

查看:78
本文介绍了replaceWith自动关闭标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个div,我想用另一个div的开始标记替换第一个div,用结束标记替换第三个div。这就是我的意思:

I have 3 divs and I want to replace the first div with an opening tag of another div and the third with the closing tag. This is what I meant:

<div>1</div>
<div>2</div>
<div>3</div>

当我尝试替换(使用replaceWith())第一个div < div class =foo> 和第三个< / div> ,jQuery有点误解为:

When I tried to replace (using replaceWith()) the first div with <div class="foo"> and the third with </div>, jQuery somewhat misinterpret it as:

<div class="foo"></div>
<div>2</div>
</div>

虽然我真正想要的是:

<div class="foo">
 <div>2</div>
</div>

提前谢谢,

推荐答案

您应该使用整个元素而不是HTML代码。另一种思考方式是:

You should work with whole elements rather than pieces of HTML code. Another way to think about it is:

// Get the div you want
var good = $('div:eq(1)');
// Remove the others
$('div').not(good).remove();
// Wrap the div you want
good.wrap('<div class="foo">');

如果第一个和最后一个之间有多个div,您可以这样做:

If there are multiple divs between the first and the last, you may do this:

$('div:first').replaceWith('<div class="foo">');
$('div.foo').nextAll('div').appendTo('div.foo');
$('div.foo :last').remove();

参见演示: http://jsfiddle.net/TBMHt/

这篇关于replaceWith自动关闭标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆