gpt4 book ai didi

javascript - (Javascript) 按钮没有更新

转载 作者:行者123 更新时间:2023-11-30 12:14:50 24 4
gpt4 key购买 nike

我有一个成分列表和显示的选定成分。当我点击一种成分时,我希望它显示在我选择的成分下方,当我点击所选成分时,我希望它返回。

这就是我目前所拥有的。 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();

最佳答案

moveToOther 的参数没有用引号引起来,因此它们被解释为变量名。例如,如果单击“eggs”按钮,控制台中将显示错误消息 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/ .

关于javascript - (Javascript) 按钮没有更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32685811/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com