Trying jQuery wrapAll seems to wrap the content twice

不羁岁月 提交于 2019-12-10 19:43:25

问题


I got a markup looking like this :

<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>

I want it to end up that way :

<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>

So I can populate #isolated-component and easily discard them from a jQuery selection.

I tried that :

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

But ended up with :

<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>

回答1:


Ok, I found why. When you move the body content to the DIV, it moves the script tags including the JS moving the stuff and lead the script to execute a second time. Now I don't know why this doesn't end up in a infinite loop, but it's good to know : don't ever move script tags, you will make them reload.




回答2:


I'm not sure if this will fix your problem but you should use wrapInner:

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


来源:https://stackoverflow.com/questions/1543249/trying-jquery-wrapall-seems-to-wrap-the-content-twice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!