首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Buttons无法正常工作

Buttons无法正常工作
EN

Stack Overflow用户
提问于 2015-01-21 11:22:25
回答 1查看 70关注 0票数 0

请容忍我,因为我刚刚接触Javascript,而且我在JavaScript的面向对象编程方面完全是新手,所以……有人能帮我解决我的问题吗?(请原谅代码中的长度和注释)

首先:我已经创建了两个对象:产品,篮子通过'createProductRows()‘函数传入一个产品对象数组在加载时创建了一个表。这将打印出产品信息并创建一个按钮,该按钮将产品添加到篮子中。这是按钮(或其他东西)给我的问题。*我希望按钮使用productList数组中的产品索引调用addProduct()函数,而该数组又调用篮子对象中的两个函数: addToBasket()和display()。这应该会将创建的元素添加到购物篮表中

我不确定我是否正确地传递了productList数组,或者也许我应该使用篮子方法的原型,任何帮助让它正确工作的人都将不胜感激。谢谢

代码语言:javascript
复制
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;
        };
    };
};
EN

回答 1

Stack Overflow用户

发布于 2015-01-21 12:23:57

更新

在您的案例中,问题可能出在您创建闭包的方式上:

代码语言:javascript
复制
btn.onclick = function() {addProduct(i);};

您可以尝试登录并查看控制台,查看i的值是什么:

代码语言:javascript
复制
btn.onclick = function() {console.log('and i is:',i);addProduct(i);};

当在循环中创建闭包时,i的值并不是您所认为的值,您可能可以通过使用IIFE来解决它:

代码语言:javascript
复制
btn.onclick = (function(index) {
  return function(){
    console.log('and index is:',index);
    addProduct(index);
  };
}(i));

设置事件处理程序的问题是你得到了错误的调用对象。

下面是关于调用对象的以下answer的副本:

this变量

在所有示例代码中,您都会看到这指的是当前实例。

this变量实际上指的是调用对象,它指的是函数之前的对象。

为了解释清楚,请参阅以下代码:

代码语言:javascript
复制
theInvokingObject.thefunction();

在附加事件侦听器、回调或超时和间隔时,通常会引用错误的对象。在接下来的两行代码中,我们传递函数,但不调用它。传递函数是: someObject.aFunction,调用函数是: someObject.aFunction()。this值不是指在其上声明该函数的对象,而是指调用该函数的对象。

代码语言:javascript
复制
setTimeout(someObject.aFuncton,100);//this in aFunction is window
somebutton.onclick = someObject.aFunction;//this in aFunction is somebutton

要做到这一点,在上面的情况下引用someObject,你可以直接传递一个闭包而不是函数:

代码语言:javascript
复制
setTimeout(function(){someObject.aFuncton();},100);
somebutton.onclick = function(){someObject.aFunction();};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28059091

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档