jquery在div中使用id和操作附加div

pel*_*ive 22 html jquery

经过2个小时的搜索,我决定问我的问题.

我有一个div:

<div id="box"></div>
Run Code Online (Sandbox Code Playgroud)

我想使用jquery在上面的div中添加一个div.

我试过(以下代码在函数内部):

var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$('div', e).attr('id', 'myid');
$("#box").append(e);
Run Code Online (Sandbox Code Playgroud)

但访问$("#myid")无效.

关于如何在div中添加div并能够操纵它们的任何想法?

谢谢!

Moe*_*eet 36

这只是错误的订单

var e = $('<div style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$('#box').append(e);    
e.attr('id', 'myid');
Run Code Online (Sandbox Code Playgroud)

首先附加然后访问/设置attr.

  • 我只是想解决原来的问题,而不是改进它. (7认同)