2013-06-28 3 views
0

я функция определяется следующим образом -Jquery Еогеасп передать переменную

function populate() { 
     $('input[id^=User]:visible').each(function() { 
      currentVal = this.val; 
      if (this.id == 'User.FirstName') { 
       $('input[id*=FirstName]:visible').each(function (currentVal) { 
        if (this.id.indexOf("User") < 0) 
         this.value = currentVal; 
       }); 
      } 
     }); 
    } 

По сути то, что я пытаюсь сделать это для каждого элемента, начиная с User Я хочу, чтобы заполнить контур через другой набор элементов и назначить их на значение из родительского цикла. Проблема проходит currentval во второй foreach - по какой-то причине она заканчивается 0,1,2.

Очевидно, что я не понимаю что-то очень важное в jQuery, но я не могу сформулировать это достаточно, чтобы Google был полезным, я пробовал. Спасибо!

ответ

1

$.each принимает 2 аргумента. 1-й из них является индексом, а второй является элементом, и вы переписываете свой currentVal из аутсорса с аргументом, определенным как аргумент во внутренней области обратной функции каждой функции внутри каждого обратного вызова.

function populate() { 
     $('input[id^=User]:visible').each(function() { 
      currentVal = this.value; //<-- Not val it should be value 
      if (this.id == 'User.FirstName') { 
       $('input[id*=FirstName]:visible').each(function() {//<-- and here 
        if (this.id.indexOf("User") < 0) 
         this.value = currentVal; 
       }); 
      } 
     }); 
    } 

Краткая ехрп с кодом:

function populate() { 
     $('input[id^=User]:visible').each(function() { 
      currentVal = this.val; 
//<-- Ok now this currentVal is available in this scope and for its subsequest each, but wait 
      if (this.id == 'User.FirstName') { 
       $('input[id*=FirstName]:visible').each(function (currentVal) { 
//<-- Now you defined the index argument of second each loop as the same variable name so this variable inside this callback takes a new scope and not the one from its parent each. 
        if (this.id.indexOf("User") < 0) 
         this.value = currentVal; 
       }); 
      } 
     }); 
    } 
1

Вы должны прочитать документацию по Jquery each() функции.

обратного вызова принимает два параметра, index и value, так currentVal получает 0,1,2, потому что у вас есть массив с 3 записей (индекс 0, 1 и 2)

function populate() { 
    $('input[id^=User]:visible').each(function() { 
     currentVal = this.val; 
     if (this.id == 'User.FirstName') { 
      $('input[id*=FirstName]:visible').each(function (idx, val) { 
       if (this.id.indexOf("User") < 0) 
        this.value = currentVal; 
      }); 
     } 
    }); 
}