2011-10-27 61 views
19

經過2個小時的搜索我決定問我的問題。jquery追加內部div div與ID和操縱

我有一個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); 

但訪問$( 「#身份識別碼」)是行不通的。

關於如何在div中添加div並能夠操縱它們的任何想法?

謝謝!

回答

29

這只是錯誤的順序

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

追加,然後再接入/ SET ATTR。

+0

爲什麼只需要三行代碼?爲什麼隨後將id附加到源HTML中? – jfriend00

+7

我只是想解決原來的問題,而不是改進它。 –

+0

我希望OP能看到改進的方式。 – 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/

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); 
+0

'.html()'方法接受一個字符串,而不是一個jQuery對象,因爲它是參數。 – jfriend00

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字符串中,而不是使用單獨的代碼來設置它。

這兩個.html().append() jQuery方法可以採取一個HTML字符串,因此不需要使用單獨的步驟來創建對象。