Javascript 使用jQuery将div附加到文档末尾?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6650963/
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-08-23 22:38:02  来源:igfitidea点击:

Append div to end of document with jQuery?

javascriptjquerydom

提问by Vivian River

I would like to write a function using jQuery to append a divto the end of a web page. I would like to be able to use the function on many different pages.

我想使用 jQuery 编写一个函数来将 a 附加div到网页的末尾。我希望能够在许多不同的页面上使用该功能。

I've written the following code, but it doesn't work:

我已经编写了以下代码,但它不起作用:

    $(document).append('<div id="helloDiv"></div>');
    $('#helloDiv').html('hello'); // does nothing
    $('#helloDiv').css('top','100') // throws an error

How do I fix this?

我该如何解决?

回答by lonesomeday

It is meaningless to append to the document. Append to the document's bodynode instead, since this is where all the visible content is:

附加到document. 改为附加到文档的body节点,因为这是所有可见内容所在的位置:

$(document.body).append('<div id="helloDiv"></div>');

回答by pimvdb

If you want it to be at the end of the body, why not use:

如果您希望它位于 的末尾body,为什么不使用:

$('body').append('<div id="helloDiv"></div>');
$('#helloDiv').html('hello');
$('#helloDiv').css('top', 100);

http://jsfiddle.net/ptuxX/

http://jsfiddle.net/ptuxX/

However, just .css('top', 100)does not do much unless you set the positionto absolute.

然而,只是.css('top', 100)并没有做太多,除非你设定的positionabsolute

回答by Jules

Try:

尝试:

$('body').append('<div id="helloDiv"></div>');
$('#helloDiv').html('hello');
$('#helloDiv').css('top', '100');

Or just add the content and it's css before adding the div.

或者只是在添加 div 之前添加内容和它的 css。

var $newdiv = '<div id="helloDiv">hello</div>';
$('body').append($newdiv);