问题描述
有趣的问题是,虽然优化了一些代码,但是使用javascript循环而不是jQuery循环来解决范围问题.
Interesting issue here, optimising some code but am having trouble with scope issues using a javascript loop as opposed to a jQuery loop.
例如,如果使用javascript循环,我们进行了3次十年"迭代,其值分别为"1950","1960"和"1970",则将得到"1970"(循环中的最后一次迭代)时间为十年的警报",但是使用jQuery.each,我们为每个创建的元素都获得了期望的值.
If for example we have 3 "decade" iterations, with values "1950", "1960", and "1970", using the javascript loop, we would get "1970" (the last iteration in the loop) all the time on the "alert" of decade.name, but using jQuery.each we get the expected value for each created element.
问题:-为什么此方法适用于jQuery.each而不是常规的javascript循环?-如何使用普通的JavaScript for循环使它正常工作?
Questions:- why does this work with jQuery.each and not regular javascript loop?- how can i make this work with a normal javascript for loop?
$.ajax({
async: true,
type: 'post',
url: 'ajax/products.php',
data: {
'action': 'get_filter_decades',
'data': {
"search_term": ple.find('input[name="search_term"]').val(),
"first_letter": $.bbq.getState('first_letter'),
"category_id": categoryId.val(),
"original_release_year_range": ple.find('input[name="original_release_year_range"]').val()
}
},
success: function (jsonResponse) {
if (jsonObj = handleJsonResponse(jsonResponse)) {
var filterDecadesResultList = filterDecades.find('ul.decade_result_list');
filterDecadesResultList.hide();
filterDecadesResultList.empty();
var originalReleaseYearRange = $(ple.find('input[name="original_release_year_range"]'));
// jquery loop
//$( jsonObj.data.decades ).each( function( i, decade ) {
// javascript loop (faster!)
var decadesLength = jsonObj.data.decades.length;
var listElement;
var linkElement;
var decade;
for (var i = 0; i < decadesLength; i++) {
decade = jsonObj.data.decades[i];
listElement = $('<li />');
linkElement = $('<a />');
linkElement.text(decade.name);
if (decade.product_count > 0) {
linkElement.append(' (' + decade.product_count + ')');
if (decade.selected) {
linkElement.addClass('selected');
}
linkElement.on("click", function () {
alert(decade.name);
if (!linkElement.hasClass('selected')) {
originalReleaseYearRange.val(decade.name);
$.bbq.pushState({
'original_release_year_range': decade.name
});
productListPaginate(ple);
} else {
originalReleaseYearRange.val('');
$.bbq.removeState('original_release_year_range');
productListPaginate(ple);
}
});
}
listElement.append(linkElement);
filterDecades.find('ul.decade_result_list').append(listElement);
// jquery loop
//});
// javascript loop
}
filterDecadesResultList.show();
}
}
});
推荐答案
请考虑以下示例: http://jsfiddle.net/9vZUg/1/
var years = [2010, 2011, 2012];
for (var i=0; i<years.length; i++) {
var year = years[i];
var input = document.createElement("input");
input.type = "button";
input.value = year;
input.onclick = function(){
alert(year); // at this point year will be always be 2012
}
document.body.appendChild(input);
}
之所以发生这种情况,是因为我们在某一时刻创建了函数,但稍后再使用它.现在,我们称年份始终是2012年,就像上一次迭代一样.我们该如何解决?创建闭包:
That happens because we create function at one point but use it later on. And at the moment we are calling it year is always 2012 as it was on the last iteration.How can we fix it? Create closure:
var years = [2010, 2011, 2012];
for (var i=0; i<years.length; i++) {
(function(){
var year = years[i];
var input = document.createElement("input");
input.type = "button";
input.value = year;
// now year is stored here and would be unique for each handler
input.onclick = function(){
alert(year);
}
document.body.appendChild(input);
})();
}
这篇关于jQuery.each和普通for循环之间的javascript/jquery范围差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!