jquery第三期:js与jquery对象转换

时间:2023-03-09 04:02:53
jquery第三期:js与jquery对象转换

我们开始进入jquery的学习了,jquery的学习就不那么中规中矩了,我们来看一个和javascript有所区别的地方。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript">
window.onload = function()
{
alert("niujiabin");
} window.onload = function()
{
alert("bcd");
} </script>
</head>
<body>
</body>
</html>

结果是:

弹出niujiabinbin的提示框,但是我们改写成jquery:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript">
$(function()
{
alert("abc"); });
$(function(){ alert("bcd");
}); </script>
</head>
<body>
</body>
</html>

结果却是两个都输出了,我们可以看出,jquery的加载方式进行了变化,那么这样的好处是什么呢?

如果引用两个js文件的function,那么会产生覆盖问题,jquery使用闭包解决了此问题。

下面我们看一看js对象和jquery对象:

下面的代码能找出错误么?

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript">
$(function()
{
var hello = document.getElementById("hello");
hello.css("color","red");
});
</script>
</head>
<body>
<div id="hello">
<ul>
<li>niujiabin</li>
<li class="abc">maybe</li>
<li>gossipgo</li>
</ul>
</div> </body>
</html>

运行会出现错误:

jquery第三期:js与jquery对象转换

也就是说我们的js对象并不能调用jquery的方法,那么怎么把js对象转换成jquery对象呢,很简单,加入$() 就可以了:

$(hello).css("color","red");

运行结果:

jquery第三期:js与jquery对象转换

那么jquery对象怎么转换成js对象呢,我们可以把jquery对象想成一个数组,请看代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript">
$(function()
{
($("li.abc")[0]).innerHTML = "niujiabinaaaa";
});
</script>
</head>
<body>
<div id="hello">
<ul>
<li>niujiabin</li>
<li class="abc">maybe</li>
<li>gossipgo</li>
</ul>
</div> </body>
</html>
($("li.abc")[0]).innerHTML = "niujiabinaaaa";
//li.abc取出一个jquery对象,因为他就有一个元素我们得到第一个,在后面加一个[0],就变成了js对象,
//最后调用js的innerHTML方法。

运行结果:

jquery第三期:js与jquery对象转换