jQuery .each() - 实际用途?

问题描述 投票:0回答:8

我正在努力更好地理解 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 );
    });
});

您在代码中使用的 .each 方法的实际用途有哪些示例? $(this) 到底代表什么?

jquery
8个回答
56
投票

注意 jQuery 的 each 有两种类型,一种迭代并返回 jQuery 对象,另一种是更通用的版本。

核心/每个
示例:创建页面上所有 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);

实用程序/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 );
});

9
投票

我有时用它来遍历 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()
      });

效果非常好。


6
投票

一个简单的用法,但对于迭代表和条带化交替行非常方便:

// 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");
    }
});

6
投票

我使用

.each()
方法进行 ASP.NET
WebMethod
调用,返回 JSON 字符串。在此示例中,它使用 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 有一个内置的 JSON 序列化器,可以自动将类转换为您在本文底部看到的 JSON 字符串。 这是一个可由

WebMethod
返回的示例类:

public class Tuple
{
    public string Text;
    public int Value;

    public Tuple(string text, int val)
    {
        Text = text;
        Value = val;
    }
}

还有

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;
}

当您在 jQuery Ajax 选项中指定

dataType: "json"
时,字符串会自动转换为 Javascript 对象,因此您只需键入
this.Text
this.Value
即可获取数据。

这是从上面的

WebMethod
返回的结果 JSON:

{"d":[{"Value":1,"Text":"First option"},{"Value":2,"Text":"Second option"}]}

注意:

data.d
参数(以及同样在 JSON 字符串中看到的第一个值)在 here 进行了解释。


3
投票

$.each()
用作for循环,
$(this)
引用循环的当前对象。在下面的示例中,我们循环遍历表行
$(this)
表示它迭代的当前行。

循环数组

// here's the array variable
 var myArray = ["apple", "mango", "orange", "grapes", "banana"];

 $.each(myArray, function (index, value) {
      console.log(index+' : '+value);
 });

循环表格行(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);
 });

我的文章了解 jQuery .each()


2
投票

each()
是一个迭代器函数,用于循环对象、数组和类数组对象。普通对象通过其命名属性进行迭代,而数组和类数组对象通过其索引进行迭代。

例如:

使用 .each() 方法进行数组迭代

$.each( arr, function( index, value ){
  //code here
});

使用 .each 方法进行普通对象迭代

$.each( { firstName: "Amit", lastName: "Gupta" }, function(firstName, lastName){
    console.log( " First Name: " + firstName + " Last Name: " + lastName);
});

1
投票

您可以使用each函数来访问/修改任何未被jquery包装的dom属性。

我经常有一个网格/表格,其中有一列包含复选框。

我编写一个选择器来获取复选框列表,然后将选中的属性设置为 true/false。 (要选中全部,请取消选中全部)。

您必须使用每个功能。

$(".mycheckbox").each(function() { this.checked = true; });


1
投票

以下是教程链接:

$(function(){
            var ArrList=["Jaipur","Udaipur","Kota","Ahmedabad","Surat"];
                $(ArrList).each(function(index,item){
                    $("ul").append("<li>"+item+"</li>");
                });
        });

https://www.youtube.com/watch?v=qiYdTv_sZyU

© www.soinside.com 2019 - 2024. All rights reserved.