1. 程式人生 > >通過js獲取td標籤的text、html、innerhtml三者的區別

通過js獲取td標籤的text、html、innerhtml三者的區別

注意innerhtml是原生的js的用法。

text、html是jQuery的用法,原生的js語法是沒有text、html這種用法的。

原生的innerhtml = jQuery的html()

html()獲取的是id=?的標籤如<td id="test"><a>www.baidu.com</a></td>中的html程式碼,即<a>www.baidu.com</a>。

text()獲取的是id=?的標籤如<td id="test"><a>www.baidu.com</a></td>中的遮蔽掉標籤後的text值,即www.baidu.com。

val()獲取的是id=?的標籤的value屬性的值,如果沒有value屬性,該方法不起作用,即表現為獲取不到值。

例子:

<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
function changeLink()
{
alert(document.getElementById('test').innerHTML);//結果是:<a id="myAnchor" href="http://www.microsoft.com">訪問 Microsoft</a>
alert($("#test2").html());//結果是:<a id="myAnchor" href="http://www.microsoft.com">訪問 Microsoft</a>
alert($("#test2").text());//結果是:訪問 Microsoft
alert($("#test2").val());//該方法不起作用,因為td沒有value屬性。val是獲取的value屬性的值,多用於input。
alert($("#test5").val());//結果是:123
}
</script>
</head>


<body>
<table>
<tr>
<td id="test">
<a id="myAnchor" href="http://www.microsoft.com">訪問 Microsoft</a>
<td>
<td id="test2">
<a id="myAnchor" href="http://www.microsoft.com">訪問 Microsoft</a>
<td>
<td id="test3">
<input id="test5" value="123" />
<td>
</tr>
</table>
<input type="button" onclick="changeLink()" value="改變連結">


</body>


</html>