JQuery中$.each 和$(selector).each()的区别详解

2020-05-22 21:57:22易采站长站整理

       return (this != “three”); // 如果this = three 则退出遍历
   });
    jQuery.each(obj, function(i, val) {  // i 指向键, val指定值
      $(“#” + i).append(document.createTextNode(” – ” + val));
    });
</script>
</body>
</html>
// 输出
 
Mine is one. – 1
Mine is two. – 2
Mine is three. – 3
– 4
– 5

例子:———遍历数组的项, 传入index和value

<!DOCTYPE html>
<html>
<head>
<script src=”http://code.jquery.com/jquery-latest.js”></script>
</head>
<body>
<script>
$.each( [‘a’,’b’,’c’], function(i, l){
alert( “Index #” + i + “: ” + l );
});
 
</script>
</body>
</html>

例子:———遍历对象的属性,传入 key和value


<!DOCTYPE html>
<html>
<head>
<script src=”http://code.jquery.com/jquery-latest.js”></script>
</head>
<body>
<script>
 
$.each( { name: “John”, lang: “JS” }, function(k, v){
alert( “Key: ” + k + “, Value: ” + v );
});
 
</script>
</body>
</html>

正自评论的例子


1. 如果不想输出第一项 (使用retrun true)进入 下一遍历
 
<!DOCTYPE html>
<html>
<head>
<script src=”http://code.jquery.com/jquery-latest.js”></script>
</head>
<body>
<script>
 
var myArray=[“skipThis”, “dothis”, “andThis”];
$.each(myArray, function(index, value) {
if (index == 0) {
return true; // equivalent to ‘continue’ with a normal for loop
}
// else do stuff…
alert (index + “: “+ value);
});
 
</script>
</body>
</html>