Jquery 如何用复杂的结构包装HTML元素?
我有一个html元素,需要用以下结构将其包装:Jquery 如何用复杂的结构包装HTML元素?,jquery,html,Jquery,Html,我有一个html元素,需要用以下结构将其包装: <div class="someclass"> <div class="somewrapper"> <div class="foo"></div> <div class="bar"> <div class="foobar1"></div> <div class="fooba
<div class="someclass">
<div class="somewrapper">
<div class="foo"></div>
<div class="bar">
<div class="foobar1"></div>
<div class="foobar2"></div>
</div>
<div class="anotherclass"></div>
<div class="yetanotherclass">
<!-- the element to be wrapped should go here -->
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
</div>
<div class="anotherwrapper">
<div class="clearfix"></div>
</div>
<div class="clearfix"></div>
</div>
页面上存在的我的HTML元素应该由上述结构包装,并以.yetanotherclass
结束
我已经研究了jQuery的wrap()
函数的所有变体,但它似乎不支持这种需求(如果我错了,请纠正我)
[编辑]
上面提供的HTML块是通过javascript构建的,在页面上不可用(此时,它保存在一个变量中)。另外,还有一些绑定到html元素的事件需要包装,如果我不需要重新绑定就好了。。我想追加/复制/删除可能会起作用,但看起来有点混乱。您可以尝试使用
.prepend()
$('.yetanotherclass').prepend('somehtml');
如果您有javascript中的html代码,则可以将其存储在一个变量中,并按如下方式预先添加该元素:
var html = '<div id="yournewelement">some html</div>';
$('.yetanotherclass').prepend(html);
var html='some html';
$('.yetanotherclass').prepend(html);
更新
请尝试以以下方式包装代码:
$('#elementtobewrapped').nextUntil('.clearfix').andSelf().wrapAll('<div class="yetanotherclass" />');
$('#elementtobewrapped').nextUntil('.clearfix').andSelf().wrapAll('');
从字符串(或jQuery对象)中获取模板,或使用脚本标记将其作为模板保存,或从页面中的容器中获取模板
用$()
然后插入所需的html
$template.find('.yetanotherclass').html( /* source of content*/)
$('#someElement').append($template)
我的做法是将包装器模板存储在DOM中(作为隐藏字段或非标准脚本标记),然后在需要时克隆它。这样,您就不必在JS文件中创建这个巨大的HTML元素
也就是说,您完全可以创建每个div,并按正确的顺序追加/追加它们 我唯一能想到的就是这样 元素
<button>Button</button>
按钮
剧本
$('button').replaceWith($('<div class="someclass"><div class="somewrapper">' +
'<div class="foo"></div><div class="bar"><div class="foobar1"></div>' +
'<div class="foobar2"></div></div><div class="anotherclass"></div>' +
'<div class="yetanotherclass">' + $('button')[0].outerHTML + '<div class="clearfix"></div></div>' +
'<div class="clearfix"></div></div><div class="anotherwrapper"><div class="clearfix"></div></div>' +
'<div class="clearfix"></div></div>'));
$('button')。替换为($(''+
'' +
'' +
'+$('button')[0]。outerHTML+'+
'' +
''));
使用$element.before('.yetanotherclass.clearfix')
?这会起作用,但是我提供的html结构在页面上还不存在。您可以在将html结构放在页面上后立即使用上一行。wrap不支持此功能,您必须附加新的html,然后将元素移动到它的新位置。是的。。我刚刚编辑了我的问题。我希望有更好的办法=[Thank$('.yetanotherclass')还不存在。我对帖子进行了编辑。谢谢!更新我的答案,你需要使用id或代码选择器来包装@Kennythonpson这听起来更像是一个解决方案。我担心我会丢失任何绑定到“内容源”的事件,很可能会丢失事件
<button>Button</button>
$('button').replaceWith($('<div class="someclass"><div class="somewrapper">' +
'<div class="foo"></div><div class="bar"><div class="foobar1"></div>' +
'<div class="foobar2"></div></div><div class="anotherclass"></div>' +
'<div class="yetanotherclass">' + $('button')[0].outerHTML + '<div class="clearfix"></div></div>' +
'<div class="clearfix"></div></div><div class="anotherwrapper"><div class="clearfix"></div></div>' +
'<div class="clearfix"></div></div>'));