我有一个html元素,我需要用以下结构包装它:
<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元素,如果我不需要重新绑定将会很好..我想也许一个追加/复制/删除可能会工作,但它似乎有点凌乱。
答案 0 :(得分:1)
您可以尝试使用.prepend()
$('.yetanotherclass').prepend('<div id="yournewelement">some html</div>');
如果你在javascript中有html代码,你可以将它存储在var中,并在这个元素前加上这样的元素:
var html = '<div id="yournewelement">some html</div>';
$('.yetanotherclass').prepend(html);
更新
尝试以这种方式包装您的代码:
$('#elementtobewrapped').nextUntil('.clearfix').andSelf().wrapAll('<div class="yetanotherclass" />');
答案 1 :(得分:1)
从字符串(或jQuery对象)中获取模板,或使用脚本标记将其作为模板或页面中的容器保存。
将模板html包裹在$()
var template=/* source html*/
var $template=$(template)
然后插入你想要的html。
$template.find('.yetanotherclass').html( /* source of content*/)
$('#someElement').append($template)
答案 2 :(得分:0)
我的举措是将包装器模板存储在DOM中(作为隐藏字段或非标准脚本标记),然后在需要使用它时将其克隆。这样您就不必在JS文件中创建这个巨大的HTML元素。
那就是说,你绝对可以创建每个div并以正确的顺序附加/填充它们。
答案 3 :(得分:0)
我唯一能想到的就是这样......
元素
<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>'));