2011-10-27 4 views
19

2 시간 동안 검색 한 후 내 질문을하기로 결심했습니다.jquery id가있는 div 안에 div를 추가하고 조작하면

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

내가 jQuery를 사용하여 위 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

한 줄만 쓰면 왜 세 줄의 코드를 사용해야합니까? 나중에 소스 HTML에 바로 삽입 할 수있을 때 ID를 첨부해야하는 이유는 무엇입니까? – 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>'); 

참고 : 별도의 코드를 사용하지 않고 HTML 문자열에 id="myid"을 넣습니다.

.html().append() jQuery 메서드는 HTML 문자열을 사용할 수 있으므로 개체를 만드는 데 별도의 단계를 사용할 필요가 없습니다.

관련 문제