페이지에 HTML 요소를 추가하는 자바 스크립트 함수를 고려해보십시오. 이 함수에서 요소의 HTML을 지정하는 행이 필요합니다. 그러나이 HTML이 복잡하다면 코드가보기 흉하고 어렵게 만들 수 있습니다. 다음의 예는 (같은 ul.innerHTML에주의를 재생) 고려 : 자바 스크립트 함수 내에서 HTML을 구성하기 위해이보다 더 좋은 방법은자바 스크립트 함수 내에서 HTML 구성
function addHTMLField(area,limit) {
var field_area = document.getElementById(area);
var all_inputs = field_area.getElementsByTagName("ul");
var last_item = all_inputs.length - 1;
var last = all_inputs[last_item].id;
var count = Number(last.split("_")[1]) + 1;
if(count > limit && limit > 0) return;
if(document.createElement) { //WC3 Dom method
var ul = document.createElement("ul");
ul.innerHTML = "<ul style='margin-top: 10px' id='blog_"+count+"'><li>Blogname:<br/> <input type='text' name='blog["+count+"][name]' size='40' /></li><li>Blog Title:<br/> <input type='text' name='blog["+count+"][title]' id='blogtext_"+count+"' size='40' /></li><li>Username:<br/> <input type='text' name='blog["+count+"][username]' id='blogcategory_"+count+"' size='40' /></li><li>E-Mail:<br/> <input type='text' name='blog["+count+"][email]' id='blogcategory_"+count+"' size='40' /> <br/><small>A new user will be created if the above email address is not in the database. <br/>The username and password will be mailed to this email address. </small></li><li><input type='button' value='Remove Blog' onclick=\"removeItem('blog_"+count+"')\"> </li></ul>";
field_area.appendChild(ul);
} else {
alert('an error occurred in the addLinkField function');
}
}
있습니까? 일부 필드는 동적으로 채워지기 때문에 모든 HTML을 자바 스크립트 외부로 만들 수는 없습니다.
통찰력을 주셔서 감사합니다.
ul.innerHTML을 설정하는 대신 모든 자식 노드에 document.createElement를 사용하지 않는 이유는 무엇입니까? – vit