<script>
window.onload=function () {
var Odiv=document.createElement("div") //创建一个div
var Ospan=document.createElement("span") //创建一个span
Odiv.style.cssText="width:200pxheight:200pxbackground:#636363
text-align:centerline-height:220px" //创建div的css样式
//Odiv.id="box" //创建div的id为box
//Odiv.className="Box" //div的class为Box
Odiv.appendChild(Ospan) //在div内创建一个span
document.body.appendChild(Odiv) //在body内创建一个div
}
</script>
示例如下:=====
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />
<title>无标题文档</title>
<script type="text/javascript">
var UI = {
$:function(_id){return document.getElementById(_id)},
test:function(){
var btn_input = document.createElement("input")
btn_input.type="text"
btn_input.value="自动赋值"+Math.random()
this.$("test").appendChild(btn_input)
}
}
</script>
</head>
<body>
<input type="button" value="添加文本域" onclick="UI.test()"/>
<div id="test"></div>
</body>
</html>
使用js可以先将这个input设置一个id方便取值使用jQuery可以更方便的解决这个问题。(需引入jQuery库)
所谓的动态赋值其实就是改变input的value属性。
<input type="text" name="name" id="name" />
<script type="text/javascript">
//js通过id获取html对象并赋值
doument.getElenemtById("name").value="123"//通过id获取id为name元素并修改value属性为123
//通过jquery获取html对象并赋值
$("#name").val("123")//jquery通过id属性并修改value属性为123
$("input[name='name']").val("123")//jquery通过name属性获取html对象并赋值为123
</script>
js的doument.getElenemtById()方法可以通过id直接获取到html对象
jquery则通过定义的选择器获取html对象($("#id")),这种方法更直观更简便。