如何使用javascript获取html <td>值?

Nin*_*Boy 6 html javascript

我是html和javascript的新手.

每当用户使用javascript点击表格行时,我想获取元素的内容.

test.html

<html>
<head>
<script text="text/javascript">
function dispTblContents() {
 var pName = document.getElementById("pName").value;
 var pAddress = document.getElementById("pAddress").value;
 var pEmail = document.getElementById("pEmail").value;

 alert(pName + " " + pAddress + " " + pEmail);
}
</script>
</head>

<body>
 <table>
  <thead>
        <tr>
            <th>Name</th>
            <th>Address </th>
            <th>Email</th>
        </tr>
    </thead>

    <tbody>
        <tr onclick="dispTblContents();" >
            <td id="pName">Ricardo Lucero</td>
            <td id="pAddress">Mexico City, Mexico</td>
            <td id="pEmail">rlucero@test.com</td>
        </tr>
    </tbody>

 </table>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

每当我点击它显示的行undefined undefined undefined.我知道我的代码是错的,但我真的不知道如何解决这个问题.有人能帮帮我吗.我对这件事很新.提前致谢.

mik*_*kel 12

你需要innerHTML不是value在这里,value用于表单元素.

<script text="text/javascript">
function dispTblContents() {
 var pName = document.getElementById("pName").innerHTML;
 var pAddress = document.getElementById("pAddress").innerHTML;
 var pEmail = document.getElementById("pEmail").innerHTML;

 alert(pName + " " + pAddress + " " + pEmail);
}
</script>
Run Code Online (Sandbox Code Playgroud)

如果您还没有使用它,您可能还想查看jQuery,它使用Javascript更容易地选择和操作HTML.