使用jQuery将一个div添加到具有特定id的另一个div内,并进行操作。

30

经过2小时的搜索后,我决定提问。

我有一个div:

<div id="box"></div>

我想使用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);

但是访问 $("#myid") 不起作用。

有什么办法在一个 div 中添加另一个 div 并能够操作它们吗?

4个回答

47

这只是顺序不对而已。

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');

先添加,然后再访问/设置属性。


1
为什么用三行代码,只需要一行就可以了呢?为什么之后再附加id,当它可以直接放在源HTML中呢? - jfriend00
7
我只是想解决原问题,而不是改进它。 - Moe Sweet
1
我希望原帖作者能看到有一种更好的方法来完成它。 - jfriend00

4

你把事情复杂化了:

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>');
e.attr('id', 'myid');
$('#box').append(e);

例如:http://jsfiddle.net/ambiguous/Dm5J2/

3
为什么不尝试更简单的方式,选择以下两个选项之一:
$("#box").html('<div id="myid" 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('<div id="myid" style="display:block; float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');

注意:我将id="myid"直接放在HTML字符串中,而不是使用单独的代码来设置它。
jQuery方法.html().append()都可以接受一个HTML字符串,因此无需使用单独的步骤来创建对象。

0
var e = $('<div style="display:block; id="myid" float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$("#box").html(e);

.html() 方法需要一个字符串作为参数,而不是一个 jQuery 对象。 - jfriend00

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接