jQuery 对象:就是通过 jQuery 包装 Dom 对象后产生的对象。
Dom 对象要想通过 jQuery 进行操作,先要转换为 JQuery 对象。
将 Dom 对象转换为 JQuery 对象的方法:用$函数转换, $(dom 对象 ) 。
$('#div1').html() 等价于: document.getElementById("div1").innerHTML;
如:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () { alert($("#div1").html()); })//通过$把Dom对象转换为JQuery对象,然后用html()函数,取出html代码
</script>
</head>
<body>
<div id="div1">你好啊<font color="red">朋友</font></div>
</body>
</html>
$('#div1') 得到的就是 jQuery 对象, jQuery 对象只能调用 jQuery 对象封装好的方法,不能调用 Dom 对象的方法, Dom 对象也不能调用 jQuery 对象的方法,所以alert($('#div1').innerHTML 是错的,因为 innerHTML 是 DOM 对象的属性。
jQuery 修改样式:
设置CSS样式:传参数就是设置CSS样式
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () { $("#div1").css("background","red")});
</script>
</head>
<body>
<div id="div1">你好啊<font color="red">朋友</font></div>
</body>
</html>
获得CSS样式:不传参数就是取值
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () { $("#div1").css("background", "red") });
$(function () { alert($("#div1").css("background")) });
</script>
</head>
<body>
<div id="div1">你好啊<font color="red">朋友</font></div>
</body>
</html>
![](http://hi.csdn.net/attachment/201109/7/0_13153840719Smh.gif)
在jQuery 中,为了方便记忆和使用,设置和获取都是同一个方法,用传递的参数不同来区分。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () { $("#Text1").val(new Date()); })
$(function () { alert($("#Text1").val()); });
</script>
</head>
<body>
<input id="Text1" type="text" />
</body>
</html>
类似的获得、设置 innerText 、 innerHTML 用 text() 和 html() 。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () { $("#div1").html("设<font color='Green'>置HTML</font>") })//设置
$(function () { alert($("#div1").html()) })//获取HTML
$(function () { alert($("#div1").text()) })//获取Text
</script>
</head>
<body>
<div id="div1">你好啊<font color="red">朋友</font></div>
</body>
</html>
注意: val 、html 、 text 等是方法,不是属性, jQuery 中很少有属性的用法,因为属性写法很难 “ 链式编程 ” 。