为所有a标签绑定同一个事件(闭包)

css代码:

body{text-align:center;}
body table{margin:0 auto;}
table{border-collapse:collapse; border:solid 1px Black; }
table td,th{border:solid 1px; padding:5px;}

html代码:

<html>
  <head>
    <title>user.htmltitle>

    <meta name="keywords" content="keyword1,keyword2,keyword3">
    <meta name="description" content="this is my page">
    <meta name="content-type" content="text/html; charset=GBK">

    <link rel="stylesheet" type="text/css" href="style.css">
  head>

  <body>

        <table id="usertable">
            <tr>
                <th>姓名th>
                <th>emailth>
                <th>电话th>
                <th> th>
            tr>

            <tr>
                <td>Tomtd>
                <td>[email protected]td>
                <td>5000td>
                <td><a href="deleteEmp?id=Tom">Deletea>td>
            tr>

            <tr>
                <td>Jerrytd>
                <td>[email protected]td>
                <td>8000td>
                <td><a href="deleteEmp?id=Jerry">Deletea>td>
            tr>
        table>

  body>

  <script type="text/javascript">

    //为a标签绑定事件
    //错误示例:
    /* a.onclick = function(){
        var res = confirm("你确认要删除【"+name+"】吗?");
        if(res){            a.parentNode.parentNode.parentNode.removeChild(a.parentNode.parentNode);
        }
        return false;       //阻止a标签的默认行为:跳转新标签
    }; */
    //正确方法
      var aNodes = document.getElementsByTagName("a");
      for(var i=0;ifunction(j){
                 aNodes[j].οnclick=function(){
                     var res = confirm("你确认要删除【"+aNodes[j].id+"】吗?");
                    if(res){
                    aNodes[j].parentNode.parentNode.parentNode.removeChild(aNodes[j].parentNode.parentNode);
                    }
                return false;       //阻止a标签的默认行为:跳转新标签
                }
             })(i)
        }

  script>
html>

你可能感兴趣的:(为所有a标签绑定同一个事件(闭包))