2015-09-21 47 views
1

我有一个成分和所选成分的列表显示。当我点击一种成分时,我希望它出现在我选择的成分下,当我点击所选择的成分时,我希望它返回。(Javascript)按钮没有更新

这是我到目前为止。 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(); 
+1

您必须提到代码中的问题,而不是倾销整个代码,并期望我们找到问题/清理。 – aadarshsg

回答

3

moveToOther的参数没有用引号括起来,所以他们被解释为变量名。例如,如果单击“蛋”按钮,这就是为什么错误消息Uncaught ReferenceError: eggs is not defined将出现在控制台中。

创建按钮标记线应改为这样:

Buttons += '<button onclick="moveToOther(\'' + ingredient + '\')">' + ingredient + '</button><br>'; 

的第二个问题是,你总是在删除索引元素-1,而不是被点击项目的索引。 moveToOther函数应该改为使用实际的索引。

function moveToOther(ingredient) { 
    //Save the actual index values here instead of hard-coding -1 
    var ingredientsIndex = ingredients.indexOf(ingredient); 
    var selectedIndex = selected.indexOf(ingredient); 

    if(ingredientsIndex > -1) { 
     ingredients.splice(ingredientsIndex, 1); 
     selected.push(ingredient); 
     printAllButtons(); 
    } 
    else if(selectedIndex > -1){ 
     selected.splice(selectedIndex, 1); 
     ingredients.push(ingredient); 
     printAllButtons(); 
    } 
} 

更新的JSFiddle在这里:http://jsfiddle.net/brLexrg0/

+0

非常感谢!也意识到我没有通过拼接的正确索引。 –

+0

@MarcoChan很高兴能帮到你。我的答案的第二部分涉及拼接指数。如果它解决了你的问题,不要忘记接受答案。 –