兼容IE、Chrome,Opera动态添加文本框
因为最近在做一个优惠券验证的插件,优惠券在购买多件项目后一对多模式动态生成(1个优惠券编号,多个密码),需要动态添加生成密码框,删除按钮,做的过程中发现,innerHTML累加的方式与appendChild 来做,总是不尽如意,浏览器不兼容,找了好多资料,发现了用表格 insertRow() 来做倒是不错的一个点子,记录随笔,旨在学习,以后很有可能还有遇到。
<script type="text/javascript">
var n = 1;
function addtext(id) {
var row, cell, str;
//insertRow(-1) 生成 <tbody> <tr><td> </td></tr></tbody>
row = document.getElementById("tb").insertRow(-1);
if (row!=null) {
cell = row.insertCell(-1);
cell.innerHTML = "密码" + (n + 1) + ":<input type='text' id='txt" + n + "' name='txt" + n + "' /><input type='button' id='btndel' value='删除' onclick=\"delrow(this,'tb'); \" /> ";
n++;
}
}
function delrow(obj, id) {
var curRow;
//obj.parentNode <td>
//obj.parentNode.parentNode <tr>
curRow = obj.parentNode.parentNode;
var index = curRow.rowIndex;
document.getElementById(id).deleteRow(index);
document.getElementById("").appendChild
}
</script>
<body > 密码1: <input type="text" id ="txt1" name ="txt1" /> <input type="button" id ="btnadd" onclick="addtext('td');" value="添加" /> <table id ="tb" border="1" > </table> </body>

浙公网安备 33010602011771号