Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何正确使用;这";是否在嵌套的.each()中?(JQuery)_Javascript_Jquery - Fatal编程技术网

Javascript 如何正确使用;这";是否在嵌套的.each()中?(JQuery)

Javascript 如何正确使用;这";是否在嵌套的.each()中?(JQuery),javascript,jquery,Javascript,Jquery,下面是我对的嵌套用法。每个: itemData["segmentos"] = {}; $("[id^='item-segmentos-']").each(function() { $("[id^='item-tipo-']").each(function() { itemData["segmentos"][$(outerthis).val()] = $(innerthis).val(); }); }); 如何在内部范围内使用“外部”。每个 您可以将其分配给外部函

下面是我对
的嵌套用法。每个

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

如何在内部范围内使用“外部”。每个

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

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();
    });
});

要在内部
each()
循环中使用'outer'
this
,只需将'outer'
this
缓存在变量中,然后在内部
each()
循环中引用该变量而不是使用
this

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

只是指出显而易见的问题。在您的第一个示例中,
innerthis
没有定义。@PatrickRoberts谢谢,修复了这里有一个
每个
特定的答案,在引用的副本中没有涵盖(根据我的回答,我认为这是这个特定问题的更好解决方案),因此我投票重新打开,因为不是一个完全重复的答案