简体   繁体   English

如何在jQuery .each()函数中使变量可访问?

[英]How to make variable accessible within jQuery .each() function?

This is and example of a frequent dilemma: how to make markup accessible inide this .each() ? 这是一个经常陷入困境的例子:如何在这个.each()中使markup可访问?

I'm more interested in learning how to access outer variables from within a closure than I am in this specific issue. 我更感兴趣的是学习如何从闭包内访问外部变量,而不是在这个特定的问题中。 I could fix this problem by assigning markup from inside the each function, but I'd rather learn a more elegant way to handle this kind of problem. 我可以通过从每个函数内部分配markup来解决这个问题,但我宁愿学习一种更优雅的方法来处理这类问题。

// hide form & display markup
function assessmentResults(){

  // get assessment responses
  var markup = parseForm();

  // show assessment results to user
  $('#cps-assess-form fieldset').each( function() {
    var q = $(this).find('.fieldset-wrapper');
    var i = 0;

    // hide form questions
    q.slideUp();

    // insert markup
    $('<div>'+markup[i]+'</div>').insertAfter(q);
    i++;
  });

}

Read the docs , it already has an index! 阅读文档 ,它已经有一个索引!

.each( function(index, Element) )

No need for i 不需要i

$('#cps-assess-form fieldset').each( function(index) {
    var q = $(this).find('.fieldset-wrapper').slideUp();
    $('<div/>').html(markup[index]).insertAfter(q);
});

The reason why yours is failing is the i is inside of the function so it is reset every iteration. 您失败的原因是i在函数内部,因此每次迭代都会重置。 You would need to move it outside of the function for it to work. 您需要将其移出函数以使其工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM