jQuery .each() - 实际用途?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/722815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery .each() - Practical uses?
提问by RedWolves
I am working on trying to better understand the jQuery.each()method. Here's an example I came up with, not very practical, but it performs an action on each selected item from the selected set of elements returned:
我正在努力更好地理解jQuery.each()方法。这是我想出的一个示例,不是很实用,但它对返回的选定元素集中的每个选定项目执行操作:
// Loop over each link.
$( "#links a.number" ).each(
// For each number, run this code. The "intIndex" is the
// loop iteration index on the current element.
function( intIndex ){
// Bind the onclick event to simply alert the iteration index value.
$( this ).bind ("click", function(){
alert( "Numbered index: " + intIndex );
});
});
What are some examples of practical uses of the .each method you are using in your code? What exactly does $(this) represent?
您在代码中使用的 .each 方法的实际用途有哪些示例?$(this) 到底代表什么?
回答by missaghi
Note there are two types of jQuery's each, the one iterates over and returns jQuery objects, the other is a more generic version.
请注意,每个jQuery 有两种类型,一种迭代并返回 jQuery 对象,另一种是更通用的版本。
Core/each
Example: Create a csv of all the hrefs on the page. (iterates over matching DOM elements and 'this' reffers to the current element)
核心/每个
示例:创建页面上所有 href 的 csv。(迭代匹配的 DOM 元素,'this' 指向当前元素)
var hrefs = "";
$("a").each(function() {
var href = $(this).attr('href');
if (href != undefined && href != "") {
hrefs = hrefs + (hrefs.length > 0 ? "," + href : href);
}
});
alert(hrefs);
Utilities/jQuery.each
Iterating over an array or the elements of an object: (via:
jQuery Documentation)
Utilities/jQuery.each
迭代数组或对象的元素:(通过:
jQuery 文档)
$.each( { name: "John", lang: "JS" }, function(i, n){
alert( "Name: " + i + ", Value: " + n );
});
$.each( [0,1,2], function(i, n){
alert( "Item #" + i + ": " + n );
});
回答by cgp
I sometimes use it for traversing a large number of subelements in an XML data resultset
我有时用它来遍历 XML 数据结果集中的大量子元素
my parsedData = [];
$('result', data).each(function() {
parsedData.push(
{ name: $('name', this).text(),
addr: $('addr', this).text(),
city: $('city', this).text(),
state: $('state', this).text(),
zip: $('zip', this).text()
});
That works pretty nicely.
这很好用。
回答by John Rasch
I use the .each()
method for ASP.NET WebMethod
calls that return JSON strings. In this example, it populates a listbox with the values returned from the Ajax call:
我将该.each()
方法用于WebMethod
返回 JSON 字符串的ASP.NET调用。在此示例中,它使用从 Ajax 调用返回的值填充列表框:
async: true,
type: "POST",
url: "Example.aspx/GetValues",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
var list = $('<select />');
$.each(data.d, function(){
var val = this.Value;
var text = this.Text;
list.append($('<option />').val(val).text(text));
});
$('#listbox').empty().append(list.find('option'));
},
ASP.NET has a built-in JSON serializer that automagically converts a class into the JSON string you see at the bottom of this post. Here is an example class that can be returned by the WebMethod
:
ASP.NET 有一个内置的 JSON 序列化程序,可以自动将类转换为您在本文底部看到的 JSON 字符串。这是一个可以由 返回的示例类WebMethod
:
public class Tuple
{
public string Text;
public int Value;
public Tuple(string text, int val)
{
Text = text;
Value = val;
}
}
And the WebMethod
itself:
而它WebMethod
本身:
[WebMethod]
public static List<Tuple> GetValues()
{
List<Tuple> options = new List<Tuple>();
options.Add(new Tuple("First option", 1));
options.Add(new Tuple("Second option", 2));
return options;
}
When you specify dataType: "json"
in the jQuery Ajax options, the string is automatically converted into a Javascript object, so you can simply type this.Text
or this.Value
to get the data.
当您dataType: "json"
在 jQuery Ajax 选项中指定 时,字符串会自动转换为 Javascript 对象,因此您可以简单地键入this.Text
或this.Value
获取数据。
Here is the resulting JSON returned from the WebMethod
above:
这是从WebMethod
上面返回的结果 JSON :
{"d":[{"Value":1,"Text":"First option"},{"Value":2,"Text":"Second option"}]}
Note:the data.d
parameter (and likewise the first value seen in the JSON string) is explained here.
注:该data.d
参数(以及同样在JSON字符串看到的第一个值),说明在这里。
回答by Derek Lawless
A simple use, but it's very handy for iterating over a table and striping alternate rows:
一个简单的使用,但它对于遍历一个表和条带化交替行非常方便:
// Adds CSS styling to alternate rows of tables marked with a .data class attribute.
$("table.data").each(function() {
if (!$(this).hasClass("noStriping")) {
$(this).find("tbody tr:nth-child(odd)").addClass("odd");
$(this).find("tbody tr:nth-child(even)").addClass("even");
}
});
回答by amitguptageek
each()
is an iterator function used to loop over object, arrays, and array-like objects. Plain objects are iterated via their named properties while arrays and array-like objects are iterated via their indices.
each()
是一个迭代器函数,用于循环对象、数组和类数组对象。普通对象通过它们的命名属性进行迭代,而数组和类数组对象通过它们的索引进行迭代。
For example:
例如:
Array Iteration using .each() method
使用 .each() 方法的数组迭代
$.each( arr, function( index, value ){
//code here
});
Plain Object Iteration using .each method
使用 .each 方法的普通对象迭代
$.each( { firstName: "Amit", lastName: "Gupta" }, function(firstName, lastName){
console.log( " First Name: " + firstName + " Last Name: " + lastName);
});
回答by Satinder singh
$.each()
use as for loop, and $(this)
refer the current object of the loop. Here in below example, where we loop over table row $(this)
represents the current row it iterates.
$.each()
用作 for 循环,并$(this)
引用循环的当前对象。在下面的示例中,我们循环遍历表行$(this)
表示它迭代的当前行。
Also check : 5 ways use of jQuery $.each()
还要检查:jQuery $.each() 的 5 种使用方式
Loop through an Array
遍历数组
// here's the array variable
var myArray = ["apple", "mango", "orange", "grapes", "banana"];
$.each(myArray, function (index, value) {
console.log(index+' : '+value);
});
Loop through Table Row (HTML element)
遍历表格行(HTML 元素)
$("#myTable tr").each(function () {
var self = $(this);
var col_1_value = self.find("td:eq(0)").text().trim();
var col_2_value = self.find("td:eq(1)").text().trim();
var col_3_value = self.find("td:eq(2)").text().trim();
var col_4_value = self.find("td:eq(3)").text().trim();
var result = col_1_value + " - " + col_2_value + " - " + col_3_value + " - " + col_4_value;
console.log(result);
});
回答by Vishal Suthar
Here are tutorial links:
以下是教程链接:
$(function(){
var ArrList=["Jaipur","Udaipur","Kota","Ahmedabad","Surat"];
$(ArrList).each(function(index,item){
$("ul").append("<li>"+item+"</li>");
});
});
回答by Chris Brandsma
You use the each function to access/modify any dom property that isn't wrapped by jquery.
您可以使用 each 函数来访问/修改任何未由 jquery 包装的 dom 属性。
I often have a grid/table with a column containing checkboxes.
我经常有一个包含复选框的列的网格/表格。
I write a selector to get the list of checkboxes, then set the checked property to true/false. (for check all, uncheck all).
我编写了一个选择器来获取复选框列表,然后将选中的属性设置为 true/false。(对于选中所有,取消选中所有)。
You have to use the each function for that.
您必须为此使用 each 函数。
$(".mycheckbox").each(function() { this.checked = true; });
$(".mycheckbox").each(function() { this.checked = true; });