如何正确使用"这个"在嵌套的.each()中? (JQuery的)

时间:2016-01-28 23:21:37

标签: javascript jquery

这是我.each的嵌套用法:

itemData["segmentos"] = {};
$("[id^='item-segmentos-']").each(function() {
    $("[id^='item-tipo-']").each(function() {
        itemData["segmentos"][$(outerthis).val()] = $(innerthis).val();
    });
});

我如何使用" outerthis"在内部.each的范围内?

2 个答案:

答案 0 :(得分:3)

您可以将其分配给外部函数中的变量。这将形成一个闭包,内部函数将可以访问外部变量:

itemData["segmentos"] = {};
$("[id^='item-segmentos-']").each(function() {
    var outerthis = this;
    $("[id^='item-tipo-']").each(function() {
        itemData["segmentos"][$(outerthis).val()] = $(this).val();
    });
});

但请注意,jQuery将索引和元素作为参数传递给您的回调,这可以使代码更清晰,例如。

itemData["segmentos"] = {};
$("[id^='item-segmentos-']").each(function(oIndex, outerElement) {
    $("[id^='item-tipo-']").each(function(iIndex, innerElement) {
        itemData["segmentos"][$(outerElement).val()] = $(innerElement).val();
    });
});

答案 1 :(得分:3)

使用'外部'内部this循环中的each(),您只需要缓存“外部”'}变量中的this,然后引用该变量代替在内部this循环中使用each()

itemData["segmentos"] = {};
$("[id^='item-segmentos-']").each(function() {
    var outerThis = $(this);
    $("[id^='item-tipo-']").each(function() {
        var innerThis = $(this);
        itemData["segmentos"][outerThis.val()] = innerThis.val();
    });
});
相关问题