为什么jQuery的每个循环函数都会保存对元素对象的引用 [英] Why jQuery's each loop’s function saves a reference to an element object

查看:51
本文介绍了为什么jQuery的每个循环函数都会保存对元素对象的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我发现,如果已使用jQuery对象引用设置了jQuery,则jQuery会将变量保存在each循环的函数中.例如,下面的$elem值在每种方法的第二次和第三次迭代期间保持不变,并且引用的是第一个div.

Recently I discovered that jQuery saves a variable in an each loop’s function, if it has been set with a jQuery object reference. For example below $elem value stays the same during the second and third iteration of each method, and it refers to the first div.

$("div").each(function(index) {

   //below $elem is initialized with div reference during first iteration
    if (index === 0)
       $elem = $(this);

    var text = "index: <span>" + index + ",</span> <span>$(this).html():</span> <span>" +     $(this).html() + ",</span><span> elem.html():</span> <span>" + $elem.html() + "</span>";

   $("#output").append("<li>" + text + "</li>");
 });

li span {
   color: blue;
 }
 li span:nth-child(2) {
   color: red;
 }
 li span:nth-child(4) {
   color: green;
 }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>1 DIV</div>
<div>2 DIV</div>
<div>3 DIV</div>
<br />jQuery each loop's output:
<ul id="output"></ul>

对于$elem循环的第二次迭代期间$elem不会变为nullundefined,我感到有些惊讶.按照该行为,输出每三行显示一个文本: 1 DIV .有谁知道为什么$elem在每种方法的第二次和第三次迭代期间引用第一个div? –谢谢

I was kind of surprised that $elem doesn’t become null or undefined during the second iteration of each loop. Following that behavior the output has text: 1 DIV on each three lines. Does anyone have an idea why $elem refers to the first div during second and third iteration of each method? – Thanks

推荐答案

有人知道为什么$ elem在每种方法的第二次和第三次迭代期间都引用第一个div吗?

Does anyone have an idea why $elem refers to the first div during second and third iteration of each method?

因为在第一次迭代中设置了全局变量$elem,并且此变量以后再也不会更改.因此,在循环和循环结束后,此变量将指向第一个div jQuery对象.

Because you set global variable $elem in the first iteration and this variable never changes later. So in the loop and after loop is complete this variable will point to the first div jQuery object.

请不要忘记使用var关键字声明变量.未声明但已初始化的变量变为全局变量.如您所见,它可能导致混乱和错误.

Never forget to declare variables with var keyword. Undeclared but initialized variables become global variables. As you can see it can lead to confusion and errors.

这篇关于为什么jQuery的每个循环函数都会保存对元素对象的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆