2011-10-20 51 views
6

我很新的HTML和JavaScript。如何使用javascript获取html​​值?

每当用户使用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">[email protected]</td> 
     </tr> 
    </tbody> 

</table> 
</body> 
</html> 

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

回答

11

您需要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> 

如果你还没有使用它,你可能还想研究一下jQuery,它使得用Javascript选择和操作HTML变得容易很多。

+0

使用* innerText *或* textContent *(根据情况)会更好,因此不会返回标记。 – RobG

1

尝试改变valueinnerHTML

1

尝试更改为的innerHTML的innerText

document.forms[0].getElementsByTagId("pName").innerText; 
1

一个<td>标签不具有

改为使用document.getElementById("pName").innerHTML

1

我也搜索了很多。最后,我看到教授的解决方案。这是工作的例子:

........... 
    <head>    
     <script type="text/javascript"> 

     function ChangeColor(tableRow, highLight) 
     { 
      if (highLight){ 
       tableRow.style.backgroundColor = '00CCCC'; 
      } 

     else{ 
      tableRow.style.backgroundColor = 'white'; 
      } 
     } 

     function DoNav(theUrl) 
     { 
     document.location.href = theUrl; 
     } 
     </script> 

    </head> 

    <% ArrayList<Student> students = StudentsManager.getInstance().getStudents(); %> 

    <body> 
     Choose a student <br> 

     <table> 
      <tr> 
      <td> 
      <table id = "c" width="180" border="1" cellpadding="0" cellspacing="0"> 

      <% for (Student st : students){ %> 

      <tr onmouseover="ChangeColor(this, true);" 
       onmouseout="ChangeColor(this, false);" 
       onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundC.jsp?studentId=<%=st.getStudentId()%>');"> 

       <td name = "title" align = "center"><%= st.getStudentId() %></td> 

      </tr> 
      <%}%> 

............... 

学生是含有类学生(studentId,名称)的对象的ArrayList。 该表格显示所有学生。 Befor你点击一个单元格,点击查看源代码。你会看到:

<tr onmouseover="ChangeColor(this, true);" 
      onmouseout="ChangeColor(this, false);" 
      onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundC.jsp?studentId=1');"> 

      <td name = "title" align = "center">1</td> 

     </tr> 

那么在我的情况是“1”。我还没有制作目的地页面。