JavaScript中通過id獲取標籤元素的值和獲取文字框的值
form表單中有下面的程式碼:
<form method="post" id="" action="">
<input type="text" id="username" name="username" />
<br>
<span id="namespan">username</span>
</form>
通過ID獲取id值為username的文字框的方法為:
var username = document.getElementById("username").value;
通過id獲取id值為namespan的標籤的值的方法為:
var namespan = document.getElementById("namespan").innerHTML;
從以上可以看,文字框是通過value獲取的值,標籤是通過innerHTML獲取的值;
同時,還可以通過innerHTML改變span的值:
var namespan = document.getElementById("namespan");
namespan.innerHTML="this is why we play";
那麼span標籤的值改變了,而且頁面中顯示的值也改變了
全部程式碼如下:
<html lang="en">
<head>
<script type="text/javascript">
function checkForm(){
var username = document.getElementById("username").value;
var info = document.getElementById("info").innerHTML;
var spaninfo = document.getElementById("namespan");
alert(username);
alert(info);
alert(spaninfo.innerHTML);
spaninfo.innerHTML="fuck you";
alert(spaninfo.innerHTML);
}
</script>
</head>
<body>
<form method="post" id="" action="">
<table>
<tr>
<td><input type="text" id="username" name="username" /></td>
<td><span id="namespan"></span></td>
</tr>
<tr>
<td><p id="info">this is why we play</p></td>
</tr>
</table>
<input type="button" value="click" onclick="checkForm()"/>
</form>
</body>
</html>