这个函数是如何获得索引值的

How does this function obtain the index value?

本文关键字:何获得 索引值 函数      更新时间:2023-09-26

我浏览了一个代码片段,这个匿名函数被传递了index的值和value作为参数。既然我们根本没有手动调用函数,那么这有什么用呢?(通过事件调用除外)。此外,该索引值(随后在函数中使用)源自何处?究竟是谁在传递这些价值观,它们来自哪里?

var hideCode = function houdini()
{
    var numRand = getRandom(4);
    $(".guess_box").each(function(index, value) 
    { 
        if(numRand == index)
        {
            $(this).append("<span id='has_discount'></span>");
            return false;
        } 
    });
}

编写时:

$(".guess_box").each(function(index, value) 
    { $(".guess_box").each(function(index, value) 
        {
             //do something
        }

每个函数中的索引参数都是一个迭代器,它从jquery选择器选择的项的索引0到长度-1开始。

请参阅-http://api.jquery.com/jquery.each/

来自jQuery的文档:

.each()方法旨在使DOM循环结构简洁并且不易出错。调用时,它在DOM元素上迭代它们是jQuery对象的一部分。每次运行回调时通过了当前循环迭代,从0开始。更重要的是,回调是在当前DOM元素的上下文中触发的,因此关键字this指的是元素。

这意味着,在调用$('.guess_box')之后,.each(...)在返回的数组上从0开始迭代,直到长度为1。这与在返回的数组上调用for循环非常相似。

下面的代码段显示了使用jQuery的.each()函数的迭代结果,与使用纯Javascript和for循环的类似迭代相比。

var showCode = function houdini() {
  // Prints the results of each iteration so you can see what happens.
  $(".guess_box").each(function(index, value) {
    console.log($(this).text());
  });
  // In pure JS you would do something like this, which is very similar.
  var boxes = document.getElementsByClassName('guess_box');
  for (var i = 0; i < boxes.length; i++)
    console.log(boxes.item(i));
}
$('#tester').click(function() {
  showCode();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="guess_box">test 1</div>
<div class="guess_box">test 2</div>
<div class="guess_box">test 3</div>
<div class="guess_box">test 4</div>
<button id="tester">click me</button>