日期:2014-05-16  浏览次数:20926 次

使用JavaScript和DOM创建HTML页面

一.使用JavaScript和DOM创建HTML表格

??? 1.代码

<html>
	<head>
		<title>使用JavaScript和DOM创建HTML表格</title>
	</head>
	<body>
		<div id="tableTest">
		</div>
	</body>
</html>
<script language="JavaScript" type="text/javascript">
	<!--
	//获取容器div的引用
	var container=document.getElementById("tableTest");
	//创建表格对象
	var _table=document.createElement("table");
	//设置表格属性
	_table.setAttribute("border","1");
	_table.setAttribute("borderColor","black");
	_table.setAttribute("width","200");
	//创建5行
	for(var i=0;i<5;i++){
	 var _tr=_table.insertRow(i);
	 //创建4列
	 for(var j=0;j<4;j++){
	  var _td=_tr.insertCell(j);
	  var _tn=document.createTextNode(i.toString()+j.toString());
	  _td.appendChild(_tn);
	 }
	}
	//将表格显示于页面
	container.appendChild(_table);
	//-->
</script>

??? 2.运行效果

二.使用JavaScript和DOM创建HTML单选按钮

??? 1.代码

<html>
	<head>
		<title>使用JavaScript和DOM创建HTML单选按钮</title>
	</head>
	<body>
		<form id="f1">
			<span id="radioArea">Sign</span>
		</form>
		<input type="button" value="creatTestRadioButtons" onclick="creatTestRadioButtons();" />
	</body>
	<script>
		function createRadioButtonsToSpan(dataArr, radioName, targetSpanId){
		  var targetSpan = document.getElementById(targetSpanId);
		  for (var i = 0; i < dataArr.length; i++){
		    var val = dataArr[i];
		    var input = createElement("input", radioName);
		    input.setAttribute("type", "radio");
		    input.setAttribute("value", val);
		    targetSpan.appendChild(input);
		
		    var label = document.createElement("label");
		    label.setAttribute("for", radioName);
		    label.appendChild(document.createTextNode(val));
		    targetSpan.appendChild(label);
		  }
		}
		
		function createElement(type, name){
		  var element = null;
		  try{
		    // if IE
		    element = document.createElement('<' + type + ' name="' + name + '">');
		  }
		  catch (e){}
		  if (!element){
		    //if other
		    element = document.createElement(type);
		    element.name = name;
		  }
		  return element;
		}
		
		function creatTestRadioButtons(){
		  var arr = new Array();
		  arr[0] = 5;
		  arr[1] = 6;
		  arr[2] = 7;
		  createRadioButtonsToSpan(arr, "rnap", "radioArea");
		}
	</script>
</html>

??? 2.运行效果

?