通过js获取td标签的text、html、innerhtml三者的区别

来源:互联网 发布:淘宝网店买卖 编辑:程序博客网 时间:2024/06/06 14:14

注意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>

注意:
(在使用jQuery的时候,html()、text()、val()的()不要忘了,不然返回结果有问题,)
如下





0 0
原创粉丝点击