【问题标题】:How to keep jQuery from parsing inserted HTML?如何防止 jQuery 解析插入的 HTML?
【发布时间】:2010-09-21 03:54:35
【问题描述】:

有谁知道如何阻止 jQuery 解析您通过 before() 和 after() 插入的 html?假设我有一个元素:

<div id='contentdiv'>bla content bla</div>

我想用以下方式包装它:

<div id='wrapperDiv'>
    <div id='beforeDiv'></div>
    <div id='contentDiv'>bla content bla</div>
    <div id='afterDiv'></div>
</div>

我使用下面的 jQuery/Javascript

$('#contentDiv').each( function() {
    var beforeHTML = "<div id='wrapperDiv'><div id='beforeDiv'></div>";
    var afterHTML = "<div id='afterDiv'></div></div>";  
    $(this).before(beforeHTML);
    $(this).after(afterHTML);
}

然而,这不会导致正确的包装,它会创建:

<div id='wrapperDiv'>
    <div id='beforeDiv'></div>
</div>
    <div id='contentDiv'>bla content bla</div>
    <div id='afterDiv'></div>

使用 wrap() 也不起作用,因为这会让 jQuery 在使用时更加混乱:

$(this).wrap("<div id='wrapperDiv'><div id='beforeDiv'></div><div id='afterDiv'></div></div>");

我应该如何解决这个问题?
提前致谢!

【问题讨论】:

    标签: javascript jquery html dom


    【解决方案1】:
    $('#contentDiv').each(function() {
        $(this).wrap('<div id="wrapperDiv">');
        $(this).before('<div id="beforeDiv">');
        $(this).after('<div id="afterDiv">');
    });
    

    产生:

    <div id='wrapperDiv'>
        <div id='beforeDiv'></div>
        <div id='contentDiv'>bla content bla</div>
        <div id='afterDiv'></div>
    </div>
    

    【讨论】:

    • 是的,我错过了你没有“最深节点”,但是 wrap() 方法仍然是关键。
    【解决方案2】:

    你的标记不完整...之前和之后只取完整的节点...

    您要做的是包装您的内容,这是不同的。

    你想要这个:

    .wrap(html);

    http://docs.jquery.com/Manipulation/wrap#html

    【讨论】:

    • 对不起,我忘了说,换行会产生更奇怪的结果。
    【解决方案3】:

    我认为你的做法是错误的。想想你真正想要实现的目标......

    您想用一个 div 包装所有内容。然后在前面插入 1 个 div,在后面插入 1 个 div。

    首先使用 .wrap(),然后添加相对于 content-div 的前后 div。

    如果您碰巧将实际的 HTML 作为字符串(来自 XHR 或其他东西),那么您需要按照 Douglas Mayle 的建议读出 html 并将其连接起来。

    【讨论】:

      【解决方案4】:

      对不起,这个应该是显而易见的。在您的情况下,您不能使用 wrap 因为它将原始节点粘贴到它在包装 HTML 中找到的最深节点中。你不想要那个。相反,从您的对象中读出 HTML 并将其与您所拥有的内容结合起来:

      $('#contentDiv').each( function() {
          var beforeHTML = "<div id='wrapperDiv'><div id='beforeDiv'></div>";
          var afterHTML = "<div id='afterDiv'></div></div>";
      
          // This line below will do it...
          $(this).html(beforeHTML + $(this).html() + afterHTML);
      }
      

      【讨论】:

      • 大声笑非常感谢,这几乎是完美的(不是 100% 完美,因为它将 div 保持在适当的位置,但我可以解决这个问题。谢谢)
      猜你喜欢
      • 2011-01-24
      • 1970-01-01
      • 2011-09-29
      • 2015-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多