javascript 在 <body> 标签之后插入 DIV

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6232049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:00:32  来源:igfitidea点击:

Insert DIV Just after <body> tag

javascriptjqueryinternet-explorer-7

提问by Connection

I have the following code:

我有以下代码:

<script type="text/javascript">
    $(document).ready(function() {
        $('<div id="tools" style="text-align:right;float:right;"><input type="button" value="Print this page" onclick="window.print();return false;" /><input type="button" value="Save this page" onclick="go_saveas();return false;" /></div>').insertBefore('body');
    });
</script>

Basically, I need to insert that whole Div just right after the <body>tag:

基本上,我需要在<body>标签之后插入整个 Div :

</head>
<body>
    <div id="tools"..
...

Which works in Firefox but doesn't work in IE 7, what do I have to change to fix this?

哪个在 Firefox 中有效,但在 IE 7 中无效,我需要更改什么才能解决这个问题?

回答by icktoofay

You're using insertBefore. That will try to put it between headand body; not what you want. Try prependTo.

你正在使用insertBefore. 那将尝试将它放在head和之间body;不是你想要的。试试prependTo

回答by Code Maverick

http://jsfiddle.net/XDFMt/:

http://jsfiddle.net/XDFMt/

<script type="text/javascript">
    $(document).ready(function() {

        $('<div id="tools" style="text-align:right;float:right;"><input type="button" value="Print this page" onclick="window.print();return false;" /><input type="button" value="Save this page" onclick="go_saveas();return false;" /></div>')
            .prependTo('body');

    });
</script>

回答by Jayme Tosi Neto

Instead of using insertBefore, using prependTo. This way:

使用 prependTo 而不是使用 insertBefore。这条路:

<script type="text/javascript">
    $(document).ready(function() {
        $('<div id="tools" style="text-align:right;float:right;"><input type="button" value="Print this page" onclick="window.print();return false;" /><input type="button" value="Save this page" onclick="go_saveas();return false;" /></div>').prependTo('body');
    });
</script>

The insertBefore inserts your code before the tag . That's why it gives you problems. You were lucky that Firefox corrected it to what you wanted. Now, prependTo inserts it inside your tag, but before all its content. ;)

insertBefore 在标签之前插入您的代码。这就是为什么它会给你带来问题。您很幸运,Firefox 将其更正为您想要的。现在,prependTo 将它插入到您的标签中,但在其所有内容之前。;)