【问题标题】:Trying jQuery wrapAll seems to wrap the content twice尝试 jQuery wrapAll 似乎将内容包装了两次
【发布时间】:2010-12-05 07:42:58
【问题描述】:

我的标记看起来像这样:

<body>
    <...
    a lot of tags from the web site
    ...>
    <script type="text/javascript" src="http://cdn.jquerytools.org/1.1.1/jquery.tools.min.js"></script>
    <script type="text/javascript" src="my_script.js"></script>
<body>

我希望它以这种方式结束:

<body>
    <div id="body-content">
        <...
        a lot of tags from the web site
        ...>
        <script type="text/javascript" src="http://cdn.jquerytools.org/1.1.1/jquery.tools.min.js"></script>
        <script type="text/javascript" src="my_script.js"></script>
    </div>
    <div id="isolated-component">
</div>
<body>

所以我可以填充 #isolated-component 并轻松地从 jQuery 选择中丢弃它们。

我试过了:

jQuery("body").children().wrapAll("<div id='body-content'></div>")
                        .after("<div id='isolated-component'></div>");

但最后是:

<html>
<head>
<body>
    <div id="body-content">
        <div id="body-content">
            <... page content ...>
        </div>
        <div id="isolated-component"/>
        <div id="isolated-component"/>
    </div>
    <script src="my_script.js" type="text/javascript">
    </script>
</body>
<div id="_firebugConsole" style="display: none;" FirebugVersion="1.4.3" methodName="log"/>
</html>

【问题讨论】:

  • 在什么上下文中调用您的代码。该脚本可能会在引发两次的事件中被调用,但我无法从您包含的内容中判断出来。
  • 你知道你现在实际上在使用 stackoverflow 吗?
  • 大声笑,对不起。我也将这个发布到 Doctype,我想试试这个新网站 :-)
  • 如果有人想比较从一个站点到另一个站点的 anwser:doctype.com/… 我更喜欢 SO 界面。

标签: jquery wrapall


【解决方案1】:

好的,我找到了原因。当您将正文内容移动到 DIV 时,它会移动脚本标签,包括 JS 移动内容并导致脚本第二次执行。现在我不知道为什么这不会导致无限循环,但很高兴知道:永远不要移动脚本标签,你会让它们重新加载。

【讨论】:

    【解决方案2】:

    我不确定这是否能解决您的问题,但您应该使用wrapInner

    jQuery("body").wrapInner("<div id='body-content'></div>")
        .after("<div id='isolated-component'></div>");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 1970-01-01
      • 2022-12-24
      • 1970-01-01
      相关资源
      最近更新 更多