2010-02-16 16 views
8
OperationSelector = function(selectElement) { 
    this.selectElement = selectElement; 
} 

OperationSelector.prototype.populateSelectWithData = function(xmlData) { 
    $(xmlData).find('operation').each(function() { 
     var operation = $(this); 
     selectElement.append('<option>' + operation.attr("title") + '</option>');    
    }); 
} 

¿Cómo podría acceder a OperationSelector.selectElement en el bloque de iteración?Javascript ámbito externo acceso variable

+3

Por cierto, generalmente no debería usar HTML string-slinging para crear nuevas opciones. Si el 'título' puede contener un' <'o' & ', tienes problemas (posiblemente problemas de seguridad). Usar 'new Option (operation.attr ('title'))' para crear el nodo es más simple y seguro. – bobince

+0

Bobince, gracias por su consejo! – dmitrynikolaev

Respuesta

13

Asignarlo a una variable local en el ámbito de la función antes de su función de iteración. Luego puede referenciarlo dentro de:

OperationSelector = function(selectElement) { 
    this.selectElement = selectElement; 
} 

OperationSelector.prototype.populateSelectWithData = function(xmlData) { 
    var os = this; 
    $(xmlData).find('operation').each(function() { 
     var operation = $(this); 
     os.selectElement.append(new Option(operation.attr("title"))); 
    }); 
} 
Cuestiones relacionadas