2011-10-27 22 views
19

検索の2時間後に私は質問をすることにしました。jquery idを持つdiv内にdivを追加して操作します。

私は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に追加して操作する方法については、どのような考えですか?

ありがとうございました!

答えて

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

追加最初にしてアクセス/セットattrのです。

+0

3行のコードを使用するのはなぜですか?後で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文字列を使用できるため、オブジェクトを作成するために別の手順を使用する必要はありません。

関連する問題