(Javascript)按钮未更新

时间:2015-09-21 00:43:47

标签: javascript html button

我列出了成分和所选成分。当我点击一种成分时,我希望它出现在我选择的成分下,当我点击所选成分时,我希望它能够回归。

这是我到目前为止所拥有的。 http://jsfiddle.net/inspiredtolive/ghpus6on/3/

function forEach(array, action) {
    for(var i=0; i<array.length; i++) {
        action(array[i]);
    }
}

function printIngredButtons(array, selected) {
    forEach(array, function (ingredient) {
    Buttons += '<button onclick="moveToOther(' + ingredient + ')">' + ingredient + '</button><br>';
    });

    if(!selected) {
        document.getElementById("ingred").innerHTML = Buttons;
        Buttons = "";
    }
    else {
        document.getElementById("selected").innerHTML = Buttons;
        Buttons = "";
    }
}

function printAllButtons() {
    printIngredButtons(ingredients, false);
    printIngredButtons(selected, true);
}

function moveToOther(ingredient) {
    var index = -1;
    if(ingredients.indexOf(ingredient) > -1) {
        ingredients.splice(index, 1);
        selected.push(ingredient);
        printAllButtons();
    }
    else if(selected.indexOf(ingredient) > -1){
        selected.splice(index, 1);
        ingredients.push(ingredient);
        printAllButtons();
    }
}


var ingredients = ["eggs", "cheese", "milk"];
var Buttons = "";

var selected = ["peanut butter"];


printAllButtons();

0 个答案:

没有答案