通过两天的学习,对jquery有了初步的了解,现在介绍几个小小的实例。
1.遍历数组:
jQuery.each(object, [callback])
用此方法可以遍历数组,,同时使用元素索引和内容。
其中
object:需要遍历的对象或数组
callback:每个成员/元素执行的回调函数。
例如:
<script type="text/javascript">
$(function () {
var arr=['2','4','6','8'];
$.each(arr, function (index,value) {
alert(++value);
})
})
</script>
有数组【2,4,6,8】不仅遍历了数组,还让数组的每个元素加1.
用此方法可以一步就把每个数组都找出来,十分方便。
2.通过类来改变样式:
我们可以通过用addClass和removeClass分别添加类和去掉类
例如:
我们通过鼠标事件来解释一下:
有一个div我们要使鼠标放上去的时候变色应该用
$(function () {
$('li').mouseover(function () {
$(this).addClass('a');
$('li').mouseover(function () {
$(this).addClass('a');
红色字体是用addClass进行样式添加
.mouseout(function () {
$(this).removeClass('a');
})
$(this).removeClass('a');
})
红色字体是用removeClass来去掉类同时也去掉了样式
完整的代码如下:
<style type="text/css">
li{
background-color: gray;
list-style: none;
float: left;margin-left: 2px;
border-radius: 5px 5px 0px 0px;
}
.a{
background-color: red;
}
</style>
<script type="text/javascript">
$(function () {
$('li').mouseover(function () {
$(this).addClass('a');
}).mouseout(function () {
$(this).removeClass('a');
})
})
</script>
</head>
<body>
<div>
<ul>
<li>资讯动态</li>
<li>产品世界</li>
<li>市场营销</li>
</ul>
</div>
由于效果是动态的就不在这里展示了。