2011-07-28 4 views
7
appendChild appendChild에 대해 배웠고 지금까지이 코드를 생각해 냈습니다 :

자바 스크립트 : AppendChild

var blah = "Blah!"; 
 
var t = document.createElement("table"), 
 
    tb = document.createElement("tbody"), 
 
    tr = document.createElement("tr"), 
 
    td = document.createElement("td"); 
 

 
t.style.width = "100%"; 
 
t.style.borderCollapse = 'collapse'; 
 

 
td.appendChild(document.createTextNode(blah)); 
 

 
// note the reverse order of adding child   
 
tr.appendChild(td); 
 
tb.appendChild(tr); 
 
t.appendChild(tb); 
 

 
document.getElementById("theBlah").appendChild(t);
<div id="theBlah">d</div>

그러나 저에게 Uncaught TypeError: Cannot call method 'appendChild' of null을 말하는 오류가 있습니다. 내가 뭘 잘못하고 있죠?

+2

* theBlah * 아래에 스크립트를 배치 할 수 있으며 * onload * 수신기 없이도 작동합니다. – RobG

답변

20

JavaScript를 onload 함수로 래핑 해보십시오. 그래서 일단 추가는 :

<body onload="load()"> 

그런 다음 이렇게, 부하 기능에 자바 스크립트를 넣어 :

function load() { 
    var blah="Blah!"; 
    var t = document.createElement("table"), 
    tb = document.createElement("tbody"), 
    tr = document.createElement("tr"), 
    td = document.createElement("td"); 

    t.style.width = "100%"; 
    t.style.borderCollapse = 'collapse'; 

    td.appendChild(document.createTextNode(blah)); 

    // note the reverse order of adding child   
    tr.appendChild(td); 
    tb.appendChild(tr); 
    t.appendChild(tb); 

    document.getElementById("theBlah").appendChild(t); 
} 
7

문제는 document.getElementById("theBlah") 반환 null입니다. 그 이유는 theBlah 요소를 만들기 전에 코드가 실행 중이기 때문입니다. onload 이벤트 핸들러에 코드를 삽입해야합니다.

-2

자신과 우리에게 호의를 베풀고 JQuery를 사용하십시오. 모든 것이 훨씬 간단 해집니다.

$('div.SomeDiv').append($('<table></table>').css('width','100%').append($('<tbody></tbody>').append($('<tr></tr>').append($('<td></td>').html("Blah Text"))))); // Everything else you want to add here... 
+0

JS를 사용하여 Firefox 플러그인을 일부 변경했습니다 ... JQuery에 대한 정책이 확실하지 않습니다 ... – Ryan

+0

JQuery가 Javascript로 번역되어 있습니다 ... 저는 믿기 어렵습니다. 다른 ... – Yossi

+0

아니, 그것을 알지 못했습니다. jquery에 대한 경험이나 지식이 없습니다 ... – Ryan

11

페이지로드가 완료되기 전에 스크립트가 실행 중입니다. 그래서 document.getElementById ("theBlah")가 null을 반환하는 이유입니다.

어느 JQuery와 같은 또는이 방법 prolly 최단 있지만 의해 아니다 (& COLS & 랜덤 innerText와는 U로 dinamically ... 설정된 행)

<script> 
window.onload = function() { 
    var blah="Blah!"; 
    var t = document.createElement("table"), 
    tb = document.createElement("tbody"), 
    ... 
    //the rest of your code here 
}; 
</script> 
2

적절한 방법처럼 단순히 것을 사용 테이블을 만드는 가장 빠른 것. 이 (jQuery를 늦추고되지 않음) THEAD 및 기본 자바 스크립트 1. 한 임의의 텍스트

가득있는 전체 테이블이기도

2. (함수() {})() 몸이 로딩되기 전에 코드를 실행

3.and는

5.there 클론을 이용하여 기능을 단축하는 방법 그래서 U 짧은 변수가 문서를 전달하는 기능

4.and 외부의 다른 변수들에 대한 문제가없는 노드 ... 부 더 느리고 모든 브라우저에서 지원되지 않을 수도 있습니다.

6.createDocumentFragment()를 사용하여 tr을 만듭니다. u가 많은 행을 가지고 있다면 DOM을 더 빨리 작성할 수 있습니다.

(function (d) { 
    var rows = 10, 
     cols = 3, 
     t = d.createElement('table'), 
     the = d.createElement('thead'), 
     tb = d.createElement('tbody'), 
     tr = d.createElement('tr'); 
    t.style.width = "100%"; 
    t.style.borderCollapse = 'collapse'; 
    for (var a = 0; a < cols; a++) { 
     var th = d.createElement('th'); 
     th.innerText = Math.round(Math.random() * 100); 
     tr.appendChild(th); 
    }; 
    the.appendChild(tr); 
    var f = d.createDocumentFragment(); 
    for (var a = 0; a < rows; a++) { 
     var tr = d.createElement('tr'); 
     for (var b = 0; b < cols; b++) { 
      var td = d.createElement('td'); 
      td.innerText = Math.round(Math.random() * 100); 
      tr.appendChild(td); 
     } 
     f.appendChild(tr); 
    } 
    tb.appendChild(f); 
    t.appendChild(the); 
    t.appendChild(tb); 
    window.onload = function() { 
     d.body.appendChild(t) 
    }; 
})(document) 
관련 문제