jQuery .each() - 实际用途?

Red*_*ves 36 jquery

我正在努力更好地理解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 );
    });
});
Run Code Online (Sandbox Code Playgroud)

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

mis*_*ghi 53

请注意,每种类型都有两种类型,一种是迭代并返回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);
Run Code Online (Sandbox Code Playgroud)

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 );
});
Run Code Online (Sandbox Code Playgroud)


cgp*_*cgp 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()
      });
Run Code Online (Sandbox Code Playgroud)

这很好用.


Joh*_*sch 6

我使用返回JSON字符串的.each()ASP.NET WebMethod调用方法.在此示例中,它使用从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'));
},
Run Code Online (Sandbox Code Playgroud)

ASP.NET有一个内置的JSON序列化程序,可以自动将类转换为您在本文底部看到的JSON字符串.这是一个可以通过以下方式返回的示例类WebMethod:

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

    public Tuple(string text, int val)
    {
        Text = text;
        Value = val;
    }
}
Run Code Online (Sandbox Code Playgroud)

而它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;
}
Run Code Online (Sandbox Code Playgroud)

dataType: "json"在jQuery Ajax选项中指定 时,字符串会自动转换为Javascript对象,因此您只需键入this.Textthis.Value获取数据即可.

以下是从WebMethod上面返回的结果JSON :

{"d":[{"Value":1,"Text":"First option"},{"Value":2,"Text":"Second option"}]}
Run Code Online (Sandbox Code Playgroud)

注意:此处data.d解释了参数(以及在JSON字符串中看到的第一个值).


Der*_*ess 5

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

// 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");
    }
});
Run Code Online (Sandbox Code Playgroud)