您的位置:首页 > Web前端 > JQuery

jquery - each()

2015-12-04 11:23 204 查看

.each(function)

function
Type: Function( Integer index, Element element )
A function to execute for each matched element.

[b]exmple
[/b]

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>each demo</title>
<style>
div {
width: 40px;
height: 40px;
margin: 5px;
float: left;
border: 2px blue solid;
text-align: center;
}
span {
color: red;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<button>Change colors</button>
<span></span>
<div></div>
<div></div>
<div></div>
<div></div>
<div id="stop">Stop here</div>
<div></div>
<div></div>
<div></div>

<script>
$( "button" ).click(function() {
$( "div" ).each(function( index, element ) {
// element == this
$( element ).css( "backgroundColor", "yellow" );
if ( $( this ).is( "#stop" ) ) {
$( "span" ).text( "Stopped at div index #" + index );
return false;
}
});
});
</script>

</body>
</html>


jQuery.each()

jQuery.each( array, callback )

array
Type: Array
The array to iterate over.

callback
Type: Function( Integer indexInArray, Object value )
The function that will be executed on every object.

jQuery.each( object, callback )

object
Type: Object
The object to iterate over.

callback
Type: Function( String propertyName, Object valueOfProperty )
The function that will be executed on every object.

Examples

Iterates over items in an array, accessing both the current item and its index.

$.each( [ "a", "b", "c" ], function( i, l ){
alert( "Index #" + i + ": " + l );
});

Iterates over the properties in an object, accessing both the current item and its key.

$.each({ name: "John", lang: "JS" }, function( k, v ) {
alert( "Key: " + k + ", Value: " + v );
});


  以上。

  在一些使用迭代方法生成html文档的地方,使用用each函数会事半功倍。

项目代码:(仿PHP官网搜索框部分代码)

$('#search_doc').on("keyup",function(){
//remove and add the title ,make the title show before tt-dataset
$('div.tt-menu h3').each(function(){
var $dataset = $(this);
var dataset_clo = $dataset.closest('.tt-dataset');
// locate the tag h3
if(dataset_clo.prev().is('h3')){
dataset_clo.prev().remove();
}else if($dataset.next().text() == ''){
$dataset.remove();
}
// if the category has content,then insert the title before the tt-dataset
if(dataset_clo.has('a').length){
$dataset.insertBefore(dataset_clo);
}
});
});


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: