您的位置:首页 > Web前端 > JQuery

javascript jquery 动态添加删除行 (兼容所有浏览器)

2013-01-29 00:00 597 查看
实现思路:解决name名称不能修改,索引位置困扰,动态添加的行表单域value获取不到值问题

/**重置name索引**/
function resetNameIndex(tableId,paraNames){
var html=$("#"+tableId).formhtml();

var tabTrLen=$("#"+tableId).find("tbody tr");
for(var j=0;j<paraNames.length;j++){
for(var i=0;i<tabTrLen.length;i++){
html = html.replace(paraNames[j],paraNames[j].replace("[]","["+i+"]"));
}
}
$("#"+tableId).html(html);
}

function addRow(tableId){
$("#"+tableId+" tbody tr:last").clone(true).insertBefore($("#"+tableId+" tbody tr:last"));
$("#"+tableId+" tbody tr:last").find("input").val("");
}

function delRow(th){
if($(th).parents("table").find("tbody tr").length<2)
alert("不能全部删除!");
else
$(th).parents("tr").remove();

}

/**处理特殊字符(用于jquey特殊id或name取对象)**/
String.prototype.resetStr = function(){
var newStr="";
if(this){
newStr=this.replace("[","\\[").replace("]","\\]").replace(".","\\.");
}
return newStr;
}

(function($) {
var oldHTML = $.fn.html;
$.fn.formhtml = function() {
if (arguments.length) return oldHTML.apply(this,arguments);
$("input,textarea,button", this).each(function() {
this.setAttribute('value',this.value);
});
$(":radio,:checkbox", this).each(function() {
if (this.checked) this.setAttribute('checked', 'checked');
else this.removeAttribute('checked');
});
$("option", this).each(function() {
if (this.selected) this.setAttribute('selected', 'selected');
else this.removeAttribute('selected');
});
return oldHTML.apply(this);
};
})(jQuery);

==========
<table id="tab">

<thead>

<tr>

<th>1</th>

<th>2</th>

<th>3</th>

</tr>

</thead>

<tbody>

<tr>

<td><input name="psg[].name"/></td>

<td><select name="psg[].sex"><option>11</option><option>22</option></select></td>

<td><a onclick="delPsg(this);">Ⅹ</a></td>

</tr>

</tbody>

</table>

<script>

var paras=new Array("psg[].name","psg[].sex");
resetNameIndex("tableid",paras);

</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐