天天看点

javascript中for循环中超链接a的问题

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加删除记录练习</title>
<link rel="stylesheet" type="text/css" href="ex_2_style/css.css" target="_blank" rel="external nofollow"  />
<script type="text/javascript">

/*
 * 点击一个删除,删除一个员工的超链接
 */

//获取所有的超链接
window.onload = function(){
	var allA = document.getElementsByTagName("a");

	//为每个a添加单击响应函数

	for(var i = 0;i<allA.length;i++){
		allA[i].onclick = function(){
			/*
			 * for循环会在页面加载完成之后立即执行
			 *  页面响应函数在超链接被点击时才执行
			 * 当响应执行时。for循环早已执行完毕了索引永远是3
			 */
			
			alert(allA[i]);
			return false;
		};
	}

};
           
<table id="employeeTable">
	<tr>
		<th>Name</th>
		<th>Email</th>
		<th>Salary</th>
		<th>&nbsp;</th>
	</tr>
	<tr>
		<td>Tom</td>
		<td>[email protected]</td>
		<td>5000</td>
		<td><a href="javascript:;" target="_blank" rel="external nofollow" >Delete</a></td>
	</tr>
	<tr>
		<td>Jerry</td>
		<td>[email protected]</td>
		<td>8000</td>
		<td><a href="deleteEmp?id=002" target="_blank" rel="external nofollow" >Delete</a></td>
	</tr>
	<tr>
		<td>Bob</td>
		<td>[email protected]</td>
		<td>10000</td>
		<td><a href="deleteEmp?id=003" target="_blank" rel="external nofollow" >Delete</a></td>
	</tr>
</table>

<div id="formDiv">

	<h4>添加新员工</h4>

	<table>
		<tr>
			<td class="word">name: </td>
			<td class="inp">
				<input type="text" name="empName" id="empName" />
			</td>
			
		</tr>
		<tr>
			<td class="word">email: </td>
			<td class="inp">
				<input type="text" name="email" id="email" />
			</td>
		</tr>
		<tr>
			<td class="word">salary: </td>
			<td class="inp">
				<input type="text" name="salary" id="salary" />
			</td>
		</tr>
		<tr>
			<td colspan="2" align="center">
				<button id="addEmpButton" value="abc">
					Submit
				</button>
			</td>
		</tr>
	</table>

</div>
           

继续阅读