在js中使用createElement創建HTML對象和元素


1.創建鏈接

<script language= "javascript"
var o = document.body; 
//創建鏈接 
function createA(url,text) 

var a = document.createElement( "a"); 
a.href = url; 
a.innerHTML = text; 
a.style.color =  "red"
o.appendChild(a); 

createA( "http://www.ffasp.com/","網頁教學網"); 
</script> 
 

2.創建DIV

<script language= "javascript"
var o = document.body; 
//創建DIV 
function createDIV(text) 

var div = document.createElement( "div"); 
div.innerHTML = text; 
o.appendChild(div); 

createDIV( "網頁教學網:http://www.ffasp.com/");    
</script> 
 
3.創建表單項
<script language= "javascript"
var o = document.body; 
//創建表單項 
function createInput(sType,sValue) 

var input = document.createElement( "input"); 
input.type = sType; 
input.value = sValue; 
o.appendChild(input); 

createInput( "button", "ooo"); 
</script> 
 
4.創建表格
<script language= "javascript"
var o = document.body; 
//創建表格 
function createTable(w,h,r,c) 

var table = document.createElement( "table"); 
var tbody = document.createElement( "tbody"); 
table.width = w; 
table.height = h; 
table.border = 1;    
for( var i=1;i<=r;i++) 

var tr = document.createElement( "tr"); 
for( var j=1;j<=c;j++) 

var td = document.createElement( "td"); 
td.innerHTML = i + "" + j; 
//td.appendChild(document.createTextNode(i + "" + j)); 
td.style.color =  "#FF0000"
tr.appendChild(td); 

tbody.appendChild(tr);    

table.appendChild(tbody); 
o.appendChild(table); 

createTable(270,270,9,9); 
5.創建select
jquery 的話這樣
<select id="selectid">
</select>

$(function(){
$("#selectid").click(function(){
$("#selectid").append("<option value='"+entity+"'>"+entity+"</option>");//entity 變量
});

});

js的話
function padd(){
var objOption = document.createElement("OPTION");
objOption.text= 2;
objOption.value=2;
document.getElementById("padd").options.add(objOption);
}

</script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM