2014-04-23 4 views
0

Моя страница позволяет пользователям добавлять и удалять поля ввода для ввода условий поиска. Функция, которая позволяет им добавлять их, возвращает значение. (Переменная счетчик, чтобы следить за количеством, как я хочу, чтобы ограничить поля до пяти.)Как вернуть значение из анонимной внутренней функции в JS?

я вызываю функцию нажатием кнопки здесь:

<input type="button" value="+" id="add" onclick="count = addField(count);"/> 

Как вы можете увидеть значение count возвращается в скрипт.

Ниже приведена соответствующая JS для добавления поля ввода. (Функция добавить также содержит внутреннюю функцию для удаления поля ввода)

//Starts at 1, as there is always at least one input box. 
var count = 1; 

function addField(count) { 

    //Only add if the limit is not reached: 
    if (count<=4){ 

    //Increase the count by 1, alert for demo purposes: 
    count++; 
    alert(count); 

    //Create a div to hold the new input and a new button to remove it: 
    var divv = document.createElement("div"); 
    divv.setAttribute("id", "div"+count); 
    divv.setAttribute("class", "divvv") 
    inputContainer.appendChild(divv); 

    var id = "tag"+count; 
    var newField = document.createElement("input"); 
    newField.setAttribute('type', 'text'); 
    newField.setAttribute('class', 'field'); 
    newField.setAttribute('id', id); 


    divv.appendChild(newField); 

    var deleteCont = document.createElement("div"); 
    var divId = "cont"+count; 
    deleteCont.setAttribute("id", "cont"+count); 
    deleteCont.setAttribute("class", "remCont"); 
    divv.appendChild(deleteCont); 

    var removeId = "remove"+count; 
    var remove = document.createElement("input"); 
    remove.setAttribute("type", "button"); 
    remove.setAttribute("value", "-"); 
    remove.setAttribute('class', 'remove'); 
    remove.setAttribute('id', removeId); 


    //This part is the problem, When the remove button is clicked it WILL remove the 
    //Relevant div, but I can't find a way to reduce the count after this (i.e, allow 
    //the user to re-add new fields after reaching the 5 limit and removing some. 
    //Basically it allows the user to add lets say 3 (Total now at 4). If they then 
    //remove all three it should allow them to add up to 4 again. But it will only 
    //allow one. Since the count was at 4 even after they removed 3. 
    remove.onclick = function() { 

     var element = document.getElementById("inputContainer"); 
     divv.parentNode.removeChild(divv); 
    //I tried something like: 
    // count = count - 1; 
    //But obviously the value that returns from the addField function is the count 
    //outside this inner function. 


    }; 

    deleteCont.appendChild(remove); 

    return count; 
    } 

} 

Надеется, что вы можете понять этот вопрос, если не я сделал короткое видео, чтобы проиллюстрировать это.

Демо: http://tinypic.com/player.php?v=11ad7j9%3E&s=8#.U1g7kvldVvF

ответ

1

Поскольку ваша addField функция имеет переменную count, в count переменную в глобальном масштабе не могут быть доступны, говоря count. Кроме того, когда ваша внутренняя функция ссылается на count, это будет хранимое значение в закрытии, которое не разделяется между несколькими вызовами addField. Это полезно для удаления правильного элемента, но плохо для поддержания счета. Я рекомендую это:

<input type="button" value="+" id="add" onclick="addField()"/> 

JS

//Starts at 1, as there is always at least one input box. 
var count = 1; 
var idGen = 1; // Use to ensure input ids are unique 

function addField() { // No longer passing count; 
    var id = idGen++; // Each field gets a different id; 
    count++; // Count goes up. 
    ... 
    button.onclick = function() { 
     ... 
     count--; 
    } 
    ... 
    return; // No longer returning count; 
} 

До тех пор, пока вы не нужны идентификаторы должны быть последовательными, отделяя ваши идентификаторы из вашего графа будет сделать дизайн, который легче писать и поддерживать ,

+0

Это работало очень хорошо. Идентификаторы не так важны, поскольку я использую getElementsByClassName для получения значений в полях. –

Смежные вопросы