我有一些 html 元素,我想在它之前添加一些结束标签
tag.before("</div></div>");
然后在like之后添加适当的标签重新打开它
tag.after("<div class='one'><div class='two'>");
但它似乎不起作用。它创建标签并自动关闭它们,并且根本不添加关闭标签。
为什么我需要这个?
我需要一些元素作为 body 的直接子元素,我不能手动修改 html,所以我希望它关闭它内部的所有标签,然后用适当的 .classes 重新打开它们
我的功能是(但我不确定它是否重要)
//function makes element dircet child of 'to' argument. It closes all parents and reopens'em
$.fn.escape = function(to) {
return this.each(function(){
var t = $(this);
var parents = [];
var escaped = false
var actualParent = t.parent();
//div to store cleared from content parents html
var virtualDiv = $('<div class="hide"></div>');
//while not walked to given root parent
while ( !escaped ) {
var parent = actualParent;
if ( parent.is(to) || !parent.length) { //check if there is parent and if its the one we look for
escaped = true;
} else {
parents.push( parent.clone().html('').prependTo(virtualDiv) ); //prepend clone of parent with cleared content to wirtual div
actualParent = actualParent.parent(); //remember actual parent
}
}
//get html from virtual div and remove all closing tags from it
var newOpenTags = virtualDiv.html().replace(/<\/\S+>/g, '');
//basing on tag-type of each parent, generate closing tags
var closeTags = "";
for (var i = 0; i < parents.length ; i++) {
closeTags = closeTags + "</" + parents[i].get(0).tagName.toLowerCase() + ">";
}
//put closing tags before element and put reopen tags after it
t.before(closeTags);
t.after(newOpenTags);
})
}
换句话说。如何在某些元素之前添加结束标签并在其后添加开始标签(不自动关闭它们)。