jQuery - Appending a div to body, the body is the

2019-02-05 10:40发布

When I'm adding a div to body, it's returning the body as the object and then whenever I use that - it's obviously using body. Bad.

Code:-

var holdyDiv = $('body').append('div');
$(holdyDiv).attr('id', 'holdy');

The 'id' of holdy is now being added to body... eh? What am I doing wrong.

6条回答
三岁会撩人
2楼-- · 2019-02-05 11:18
    $('body').append($('<div/>', {
        id: 'holdy' 
    }));
查看更多
贪生不怕死
3楼-- · 2019-02-05 11:22

Instead use use appendTo. append or appendTo returns a jQuery object so you don't have to wrap it inside $().

var holdyDiv = $('<div />').appendTo('body');
holdyDiv.attr('id', 'holdy');

.appendTo() reference: http://api.jquery.com/appendTo/

Alernatively you can try this also.

$('<div />', { id: 'holdy' }).appendTo('body');
               ^
             (Here you can specify any attribute/value pair you want)
查看更多
干净又极端
4楼-- · 2019-02-05 11:25

Using jQuery appendTo try this:

var holdyDiv = $('<div></div>').attr('id', 'holdy');
holdyDiv.appendTo('body');
查看更多
看我几分像从前
5楼-- · 2019-02-05 11:25
var $div = $('<div />').appendTo('body');
$div.attr('id', 'holdy');
查看更多
Bombasti
6楼-- · 2019-02-05 11:38
$('</div>').attr('id', 'holdy').appendTo('body');
查看更多
smile是对你的礼貌
7楼-- · 2019-02-05 11:43

jQuery methods returns the set they were applied on.

Use .appendTo:

var $div = $('<div />').appendTo('body');
$div.attr('id', 'holdy');
查看更多
登录 后发表回答