Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/463.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 单击按钮无法正常工作_Javascript - Fatal编程技术网

Javascript 单击按钮无法正常工作

Javascript 单击按钮无法正常工作,javascript,Javascript,请容忍我,因为我才刚刚接触JavaScript,而且我对JavaScript中的OOP是完全陌生的,所以。。。有人能帮我解决问题吗?(请原谅代码中的长度和注释) 首先:我创建了两个对象:产品、篮子 通过传递产品对象数组的“createProductRows()”函数在加载时创建表。这将打印出产品信息,并创建一个按钮,将产品添加到篮子中。是按钮(或者其他东西)给了我问题*我希望该按钮调用addProduct()函数,该函数的索引位于productList数组中,该数组依次调用2个函数;篮子对象中的

请容忍我,因为我才刚刚接触JavaScript,而且我对JavaScript中的OOP是完全陌生的,所以。。。有人能帮我解决问题吗?(请原谅代码中的长度和注释)

首先:我创建了两个对象:产品、篮子 通过传递产品对象数组的“createProductRows()”函数在加载时创建表。这将打印出产品信息,并创建一个按钮,将产品添加到篮子中。是按钮(或者其他东西)给了我问题*我希望该按钮调用addProduct()函数,该函数的索引位于productList数组中,该数组依次调用2个函数;篮子对象中的addToBasket()和display()。。这将把创建的元素添加到购物篮表中

我不确定我是否正确地传递了productList数组,或者我是否应该使用Basket方法的原型,如果能帮助我正确地工作,我将不胜感激。谢谢

var productList = []; // array where product objects are to be held
var basket;
var obj;

//product constructor
var Product = function(name, description, quantity, price, gender) { 
    obj = this; // a reference to this object //could use
    this.name = name;
    this.description = description;
    this.quantity = quantity;
    this.price = price.toFixed(2);
    this.gender = gender;
};
    //product prototypes
    Product.prototype = {
        toString: function() { return this.name.toLowerCase(); }
    };
    Product.prototype.getPrice = function() {
        return '\u00A3' + this.price;
    };
    Product.prototype.getQuantity = function() {
        return this.quantity;
    };

//instantiate new products 
var shorts = new Product('Shorts', 'Stone Wash Demin Shorts', 20, 25.90, 'F');
var bag = new Product('Bag', 'Leather Shoulder Bag', 4, 50.45, 'F');
var blouse = new Product('Blouse', 'Vintage Blue Silk Polka Dot Blouse', 8, 45.99, 'F');
var boots = new Product('Boots', 'Soft Leather Brown Ankle Boots', 3, 65.35, 'F');
var belts = new Product('Belts', 'Woven Finish Fashion Belt', 15, 21.99, 'F');
var shirt = new Product('Shirt', 'Jacquard Pattern Wrangler Western Shirt', 19, 34.87, 'M');
var shoes = new Product('Shoes', 'Suede Ankle Boots', 6, 55.00, 'M');
var trousers = new Product('Trousers', 'Izod Peach Chinos', 23, 31.75, 'M');
var belt = new Product('Belt', 'Suede Casual Belt', 4, 22.98, 'M');
var hat = new Product('Hat', 'Trilby Style Brown Woven Fix', 2, 67.80, 'M');

//push all product objects to an array
productList.push(shorts, bag, blouse, boots, belts, shirt, shoes, trousers, belt, hat);

// basket constructor
var Basket = function(container, products) { // passes in the product list
    this.container = container; // this tells me where to add the data
    this.products = products; //reference to product values
    this.quantity = []; // stores quantities in bag

    for (var i=0; i < products.length; i++) { //find product

        this.quantity[i] = 0; //amount of each product in basket

        // method to add to basket
        this.addToBasket = function(index) { //reference to the product to add
            this.quantity[index]++;
            this.products[i].quantity--; // minus one from the products list
        };

        // method to remove from basket
        this.removeFromBasket = function(index) {
            if (this.quantity[index] > 0)
                this.quantity[index]--;
                this.products[i].quantity++;
        };

        //displays product
        this.display = function () {
            for (var i=0; i < this.quantity.length; i++) {
                if (this.quantity[i] > 0) {
                    var tbl = this.container
                    var row = tbl.insertRow(tbl.rows.length); // create a row element to append cells to

                    var total_price = this.quantity[i] * this.products[i].price;
                    //cell values
                    var desc = this.products[i].description; //for each value add new cell
                    var qty = this.quantity[i]
                    var price = this.products[i].price;
                    var total = total_price;
                    var remove = createRemoveBtn();

                    var cell = tbl.rows[i].insertCell(-1); // add a new cell, inserted at end of each row
                    //append cells
                    cell.appendChild(desc);
                    cell.appendChild(qty);
                    cell.appendChild(price);
                    cell.appendChild(total);
                    cell.appendChild(remove);
                    tbl.appendChild(row); // finally append the rows to the table

                    function createRemoveBtn() {
                        var btn = document.createElement('input');
                        var buttonName = products[i].name.toUpperCase(); 
                        btn.type = 'button';
                        btn.value = 'Remove';
                        btn.id = buttonName[i]; //append button names from object name
                        btn.onclick = function() {removeProduct(i);}; //test
                    return btn; 
                    };//end function 'createRemoveBtn()'
                };//end if 'quantity'
            };//end for 'basket'
        };//end function 'this.display()'
    };//end for 'products'
};//end Object 'Basket'

//create a new instance of the Basket object
basket = new Basket(document.getElementById('basketTable').getElementsByTagName('tbody')[0], productList); // *** need to create a new container for the basket

//button functions
function addProduct(item) { //add to basket function
    basket.addToBasket(item);
    basket.display();
    alert(productList[item].name + ' added to basket');
}
function removeProduct(item) { //remove item from basket
    basket.removeFromBasket(item);
    basket.display();
    alert(productList[item].name + ' removed to basket');
}

//displays product table which is called on the body onload event
function createProductRows(products) {   // passing in productList[]

    var tbl = document.getElementById('productTable').getElementsByTagName('tbody')[0]; // reference to the table to add rows to in the table body
    for (var i=0; i < products.length; i++) { // index the productsList (iterate through 0-9)

        var myProduct = products[i]; // keep a reference to each individual product - shorts, bag, blouse, etc...
        var myRow = tbl.insertRow(tbl.rows.length); // create a row element to append cells to
        var myProperties = ['name', 'description', 'quantity', 'price', 'gender']; //store the property names of the products, references to the object data

        for (var j=0; j < myProperties.length; j++) // for each property in myProperties [0-4]
        {   
            var myCell = myRow.insertCell(j); //create table cell element
            var data = myProduct[myProperties[j]]; // store property values of products
            var node = document.createTextNode(data); //add the data to a text node 
            myCell.appendChild(node); // append text node to table cell
            myRow.appendChild(myCell); // add to end of the row
        }

        var newCell = tbl.rows[i].insertCell(-1); // create a new cell, inserted at end of each row
        newCell.appendChild(createAddBtn()); // add buttons to cells
        tbl.appendChild(myRow); // finally append the rows to the table

        function createAddBtn() {
            var btn = document.createElement('input'); 
            var buttonName = products[i].name.toLowerCase(); // to be added to the button's id value
            btn.type = 'button';
            btn.value = 'Add';
            btn.id = buttonName; //append button names from object name
            btn.onclick = function() {addProduct(i);};
            return btn;
        };
    };
};
var productList=[];//用于存放产品对象的数组
风险价值篮;
var-obj;
//产品构造师
var Product=功能(名称、说明、数量、价格、性别){
obj=this;//对此对象的引用//可以使用
this.name=名称;
this.description=描述;
这个。数量=数量;
this.price=price.toFixed(2);
这个。性别=性别;
};
//产品原型
Product.prototype={
toString:function(){返回this.name.toLowerCase();}
};
Product.prototype.getPrice=函数(){
返回“\u00A3”+此价格;
};
Product.prototype.getQuantity=函数(){
退回这个数量;
};
//实例化新产品
var短裤=新产品(“短裤”、“石洗脱棉短裤”、20、25.90、“F”);
var袋=新产品(“袋”、“皮革肩包”、4、50.45、“F”);
var衬衫=新产品(“衬衫”,“复古蓝色丝绸圆点衬衫”,8,45.99,“F”);
var boots=新产品(“靴子”、“软皮棕色踝靴”、3、65.35、“F”);
var皮带=新产品(‘皮带’、‘编织整理时尚皮带’、15、21.99、‘F’);
var衬衫=新产品(“衬衫”,“提花图案牧马人西部衬衫”,19,34.87,“M”);
var鞋=新产品('shoes','Suede Ankle Boots',6,55.00,'M');
var裤子=新产品(“裤子”、“伊佐德桃色斜纹棉布裤”、23、31.75、“M”);
var皮带=新产品(“皮带”,“麂皮休闲皮带”,4,22.98,“M”);
var hat=新产品(“帽子”,“特里比风格棕色编织固定”,2,67.80,“M”);
//将所有产品对象推送到一个数组中
推送(短裤、包、衬衫、靴子、皮带、衬衫、鞋子、裤子、皮带、帽子);
//篮式构造器
var Basket=函数(容器、产品){//在产品列表中传递
this.container=container;//这告诉我在哪里添加数据
this.products=products;//对产品值的引用
this.quantity=[];//将数量存储在袋子中
对于(var i=0;i0)
这个.数量[索引]——;
本.产品[i].数量++;
};
//展示产品
this.display=函数(){
对于(var i=0;i0){
var tbl=this.container
var row=tbl.insertRow(tbl.rows.length);//创建要将单元格附加到的行元素
var总价=此.数量[i]*此.产品[i].价格;
//单元格值
var desc=this.products[i].description;//为每个值添加新单元格
变量数量=此数量[i]
var price=this.products[i].价格;
var total=总价格;
var remove=createRemoveBtn();
var cell=tbl.rows[i].insertCell(-1);//添加一个新单元格,插入到每行的末尾
//附加单元格
附加子单元(desc);
子单元(数量);
单元格。追加子项(价格);
单元格。追加子项(总计);
附加子单元(移除);
tbl.appendChild(行);//最后将行追加到表中
函数createRemoveBtn(){
var btn=document.createElement('input');
var buttonName=products[i].name.toUpperCase();
btn.type='按钮';
btn.value='删除';
btn.id=buttonName[i];//从对象名附加按钮名
btn.onclick=function(){removeProduct(i);};//测试
返回btn;
};//结束函数“createRemoveBtn()”
};//如果“数量”结束
};//以“basket”结尾
};//结束函数“this.display()”
};//以“产品”结尾
};//结束对象“篮子”
//创建篮子对象的新实例
basket=new basket(document.getElementById('basketTable').getElementsByTagName('tbody')[0],productList);//**需要为篮子创建一个新容器
//按钮功能
函数addProduct(item){//添加到篮子函数
篮子。addToBasket(项目);
basket.display();
警报(productList[item].name+“已添加到购物篮”);
}
功能移除产品(项目){//从篮子中移除项目
篮子。从篮子(项目)中移除;
basket.display();
警报(productList[item].name+“已删除到购物篮”);
}
//显示产品
btn.onclick = function() {addProduct(i);};
btn.onclick = function() {console.log('and i is:',i);addProduct(i);};
btn.onclick = (function(index) {
  return function(){
    console.log('and index is:',index);
    addProduct(index);
  };
}(i));
theInvokingObject.thefunction();
setTimeout(someObject.aFuncton,100);//this in aFunction is window
somebutton.onclick = someObject.aFunction;//this in aFunction is somebutton
setTimeout(function(){someObject.aFuncton();},100);
somebutton.onclick = function(){someObject.aFunction();};