【问题标题】:jQuery add plain html .after() and .before()jQuery 添加纯 html .after() 和 .before()
【发布时间】:2013-09-08 02:46:32
【问题描述】:

我有一些 html 元素,我想在它之前添加一些结束标签,比如

tag.before("</div></div>"); 然后在喜欢之后添加适当的标签重新打开它

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);
    })
}

换句话说。如何在某些元素之前添加结束标签并在其后添加开始标签(不自动关闭它们)。

【问题讨论】:

  • 请创建一个小提琴
  • 为什么不yourDiv.html("&lt;/div&gt;&lt;/div&gt;"+yourDiv.html+"&lt;div class='one'&gt;&lt;div class='two'&gt;")
  • vladkras 作为 .html() 期间您的灵魂中只有 div 的内部内容发生变化 - Div 仍将位于另一个 div 中。

标签: javascript jquery html


【解决方案1】:

beforeafter 不会注入 html,它会附加元素。你要做的是wrap()元素。

【讨论】:

  • 或者附加/前置,例如,如果你想插入孩子。
  • @artistandsocial 这没有任何意义。这与 OP 正在做的事情相同,它并没有做 OP 试图做的事情。
  • 我之前/之后没写?
猜你喜欢
  • 1970-01-01
  • 2014-03-12
  • 2017-02-26
  • 2012-07-06
  • 2014-07-18
  • 2013-01-28
  • 2012-12-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多