如何为数组中的按钮实现onclick功能

时间:2014-02-10 23:31:44

标签: javascript shopping-cart addition

我试图通过在每次点击按钮上添加值来执行对grandTotal文本框的添加。但是,所有发生的事情只是执行新变量的添加而不是将变量添加到较早的总数。

以下是代码: -

<div id = "cakeHook" class="recipe1"><p id="hook1title">Chocolate Cake</p></div>
<div id=  "cookieHook" class="recipe2"><p id="hook2title">Cookie</p></div>
<div id=  "grandTotalHook" class="grandTotalBox"><p id="hook3title">Total for the day</p></div>

JS:

var chocolateCakeIngredients = [];
var ckIng1 = {iname:"Flour", rate:"&nbsp;&nbsp;&nbsp;&nbsp;($1.00/Cup)"};
var ckIng2 = {iname:"Sugar", rate:"&nbsp;&nbsp;&nbsp;&nbsp;($0.50/Cup)"};

var chocolateIngredientsArray = []; 

ckIng1.value = 1.75;
ckIng2.value = 1;

chocolateIngredientsArray.push(ckIng1);
chocolateIngredientsArray.push(ckIng2);

chocolateIngredientsArray[0].id = "button1";
chocolateIngredientsArray[1].id = "button2";

var btn1 = ckIng1;
var btn2 = ckIng2;

chocolateCakeIngredients.push(ckIng1);
chocolateCakeIngredients.push(ckIng2);

var cakeHookDiv = document.getElementById("cakeHook");

function render (ingredientList) 
{
    var container = document.createElement("div"); //Created div for displaying chocolate cake list

    cakeHookDiv.appendChild(container); //Appending the div to main hook on page, i.e. cakeHook

    //Adding ingredients list to the chocolate cake

    var containerElementUl = document.createElement ("ul");
    var containerElementLi = document.createElement ("li");
    var containerElementLiButton = document.createElement ("button");
    containerElementLiButton.innerHTML = ingredientList.iname + ingredientList.rate;
    containerElementLi.appendChild(containerElementLiButton);
    containerElementUl.appendChild(containerElementLi);
    container.appendChild(containerElementUl);
    cakeHookDiv.appendChild(container);
}

render (chocolateCakeIngredients[0]);
render (chocolateCakeIngredients[1]);
render (chocolateCakeIngredients[2]);
render (chocolateCakeIngredients[3]);
render (chocolateCakeIngredients[4]);
render (chocolateCakeIngredients[5]);

var grandTotalDiv = document.getElementById("grandTotalHook");
var container3 = document.createElement("div");
grandTotalDiv.appendChild(container3);
var containerElement3 = document.createElement("input");
containerElement3.type = "text";
containerElement3.className = "grandTotalBox";
containerElement3.id = "total";
containerElement3.value = 0;
container3.appendChild(containerElement3);

var grandTotal = document.getElementById("total").value;
var counter = 0;
var currentValue = 0;
var add = function(valueToAdd){
alert("adding: " + valueToAdd);
currentValue += valueToAdd;
document.getElementById('number').innerHTML = currentValue;

function addition () 
{
    var grandTotal = btn1.value;
    grandTotal += btn2.value;
    grandTotal += btn3.value;
    grandTotal += btn4.value;
}

btn1.onclick = addition ();

0 个答案:

没有答案