1、字符串操作
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script src="js/jquery-1.7.1.js"></script>
<script>
$(function () {
var str = ' u ';
alert($.trim(str));
})
</script>
</head>
<body> </body>
</html>
2、$.each()遍历数组和对象
<html>
<head>
<script src="js/jquery-1.7.1.js"></script> </head>
<body>
<button>输出每个列表项的值</button>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Soda</li>
</ul>
<div class="box"> </div>
</body>
</html>
JavaScript
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
var arr = [],
i = 0;
//alert(typeof (lis));
for(;i < $('li').length;i++) {
var lis = $('li').eq(i).html();
arr.push(lis);
}
//alert(arr);
$.each(arr,function (index, content) {
$('.box').html($('.box').html() + (index + 1) + '.' + content + '<br />')
}); });
});
</script>
遍历对象
$.each($.ajax(), function (name, fn) {
$('#box').html($('#box').html() + name + '.' + '<br /><br />');
})
3、$.grep()数据筛选
$(function () {
var arr = ['45','2','1','5','24','19'];
var arrGrep = $.grep(arr,function (ele, index) {
return index < 4 && ele > 3;
});
alert(arrGrep);//45,5
})
4、$.map()修改数据
<script>
$(function () {
var arr = ['4','6','2','9','11','25'];
var arrMap = $.map(arr,function (element, index) {
if(index < 5 && element < 6) {
return element +'1';
}
});
alert(arrMap);//41,21
})
</script>
5、$.inArray()获取查找到元素的下标
<script>
$(function () {
var arr = [4,11,4,5,6,6,7,8,];
var arrInArray = $.inArray(11,arr);
alert(arrInArray);//1
})
</script>
6、$.merge()合并两个数组
$(function () {
var arr = [4,11,4,5,6,6,7,8];
var arr2 = [14,111,41,5,6,6,7,8];
var arrMerge = $.merge(arr2,arr);
alert(arrMerge);//14,111,41,5,6,6,7,8,4,11,4,5,6,6,7,8
})
7、$.unique()删除重复的 DOM 元素
$(function () {
var divs = $('div').get();
divs = divs.concat($('.box').get());//get() 方法获得由选择器指定的 DOM 元素。concat()方法用于连接两个或多个字符串。
alert($(divs).size()); //size()必须要用jQuery的方法($(divs),而不是divs)
$.unique(divs);
alert($(divs).size());
})
8、.toArray()合并多个 DOM 元素组成数组
$(function () {
var lis = ($('li').toArray());
alert(lis.length);
});