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

Jquery添加删除行,两个问题
HTML code



<html>
<head>
<style type="text/css">
.bt1_mouseout {BORDER-RIGHT: #7EBF4F 1px solid; PADDING-RIGHT: 2px; BORDER-TOP:#7EBF4F 1px solid; PADDING-LEFT: 2px; FONT-SIZE: 12px; FILTER:
progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr=#ffffff, EndColorStr=#B3D997); BORDER-LEFT: #7EBF4F
1px solid; CURSOR: hand; COLOR: black; PADDING-TOP: 2px;BORDER-BOTTOM: #7EBF4F 1px solid}
.bt1_mouseover {BORDER-RIGHT: #7EBF4F 1px solid; PADDING-RIGHT: 2px; BORDER-TOP:#7EBF4F 1px solid; PADDING-LEFT: 2px; FONT-SIZE: 12px; FILTER:
progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr=#ffffff, EndColorStr=#CAE4B6); BORDER-LEFT: #7EBF4F
1px solid; CURSOR: hand; COLOR: black; PADDING-TOP: 2px;BORDER-BOTTOM: #7EBF4F 1px solid}
</style>
<script language="javascript" src="jquery-1.4.min.js"></script>
<script language="javascript">

function addRow(){
$('#tb_commodity').append("<tr><td><input type='text' size='20'/></td><td><button name='btn_add'  onclick='delRow()' class='bt1_mouseout' onmouseover='this.className="bt1_mouseover"' onmouseout='this.className="bt1_mouseout"'/>删除</button></td></tr>");
}

function delRow(){
$(this).parent().parent().remove();
}
</script>
</head>
<body>



<table id="tb_commodity">
            <tr>
              <td>描述</td>
          <td>操作</td>
            </tr>
            <tr id="ad">
              <td><input type="text" size="20"/></td>
              <td><button name="btn_add"  onclick="addRow()" class="bt1_mouseout" onmouseover="this.className='bt1_mouseover'" onmouseout="this.className='bt1_mouseout'"/>增加</button></td>
          
            </tr>
          </table>

</body>
</html>


下面这两个函数为什么会报错!
function addRow(){
$('#tb_commodity').append("<tr><td><input type='text' size='20'/></td><td><button name='btn_add' onclick='delRow()' class='bt1_mouseout' onmouseover='this.className="bt1_mouseover"' onmouseout='this.className="bt1_mouseout"'/>删除</button></td></tr>");
}

function delRow(){
$(this).parent().parent().remove();
}


------解决方案--------------------
HTML code
<style type="text/css">
.bt1_mouseout {border:solid 1px red;}
.bt1_mouseover {border:solid 1px blue;}
</style>
<script language="javascript" src="http://i.6npc.com/resource/js/jquery-1.3.2.min.js"></script>
<script language="javascript">

function addRow(){
$('#tb_commodity').append(
"<tr><td><input type='text' size='20'/></td><td><button name='btn_add'  onclick='delRow(this)'"+
" class='bt1_mouseout' onmouseover='this.className=\"bt1_mouseover\"' onmouseout='this.className=\"bt1_mouseout\"'>删除</button></td></tr>");
}

function delRow(a){
alert($(a).get(0));
$(a).parent().parent().remove();
}
</script>

------解决方案--------------------
$(this) 的问题吧。
此时S(this)已经不是你想象中的那行上的那个删除按钮了,所以应该将那个button对象本身传过来。