最近做一个小控件,比较简单,可以动态增加输入框,删除,修改输入框内容并且实现输入框的上移与下移,其中用到了JQuery插件,毕竟JQuery操纵dom比yu原生的要简单一下,话不多说,直接上代码吧
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="../js/jquery-1.9.0.min.js"></script>
<style>
.subInput{
background: green;
}
.subInput:focus{
background: red;
}
</style>
<script>
var currentIndx=0;
var dataArr=[
{text:"hello"},
{text:"haha"},
{text:"xixi"}
]
$(function(){
render();
})
function render(){ //根据数据渲染dom结构
$("#contentDiv").empty();
for (var i=0;i<dataArr.length;i++) { //遍历数组中的元素
var input=document.createElement("input");
$(input).attr("index",i); //标记标签的顺序
$(input).attr("class","subInput");
$(input).attr("value",dataArr[i].text); //设置初始值
$(input).attr("onchange","inputChange(this)"); //失去输入焦点时的响应事件
$(input).attr("onclick","inputClick(this)"); //用来刷新当前选中的顺序
$("#contentDiv").append(input);
}
}
function add(){
var obj={
text:""
}
dataArr.push(obj); //添加空的数据
render(); //重新渲染dom结构
}
function del(){
if(currentIndx){
dataArr.splice(currentIndx,1); //删除数组中当前选中的元素
render(); //重新渲染dom结构
}
}
function up(){ //元素上移
if(currentIndx!=0){
var forObj=dataArr[currentIndx-1];
dataArr[currentIndx-1]=dataArr[currentIndx];
dataArr[currentIndx]=forObj;
render();
currentIndx--;
}
}
function down(){ //元素下移
if(currentIndx!=(dataArr.length-1)){
var index=parseInt(currentIndx);
var nextObj=dataArr[index+1];
dataArr[index+1]=dataArr[index];
dataArr[index]=nextObj;
render();
currentIndx++;
}
}
function inputChange(e){
var index=$(e).attr("index");
var value=$(e).val(); //获取属性(value)的话,得不到最新的值
var obj=dataArr[index];
obj.text=value;
}
function inputClick(e){
currentIndx=$(e).attr("index"); //记录当前选中的index
}
</script>
</head>
<body>
<button onclick="add()">增加</button>
<button onclick="del()">删除</button>
<button onclick="up()">上升</button>
<button onclick="down()">下降</button>、
<div id="contentDiv" style="width: 200px;height: 300px;background: gray;margin-top: 20px;">
</div>
</body>
</html>