简体   繁体   English

仅使用HTML / JavaScript创建购物车

[英]Creating a Shopping Cart using only HTML/JavaScript

I'm not sure what to do in order to complete this project. 我不确定要完成此项目该怎么做。 I need to create a shopping cart that uses only one HTML page. 我需要创建一个仅使用一个HTML页面的购物车。 I have the table set up showing what is being sold but where I am lost is the JavaScript. 我设置了显示正在出售的商品的表格,但我迷失的地方是JavaScript。

I don't know how to link the "Add to Cart" button with all the necessary data( The name, description, and price) to be able to add it to the cart. 我不知道如何将“添加到购物车”按钮与所有必要的数据(名称,说明和价格)链接起来,以便将其添加到购物车中。 I don't need to be able to remove it from the cart, but it does need to show the total. 我不需要将其从购物车中删除,但确实需要显示总数。 After searching online for a few answers, I've tried some things but just cannot figure it out. 在网上搜索了一些答案后,我尝试了一些方法,但无法弄清楚。

Any help is definitely appreciated because I am completely lost at this point and am new to JavaScript in general. 绝对感谢您的帮助,因为到此为止我已经完全迷路了,并且对JavaScript还是陌生的。

This is the jsFiddle but that was a little confusing to me, because it's working differently on there than if I just went to Run in Notepad++ 这是jsFiddle,但是这让我有些困惑,因为它在这里的工作方式与我刚进入Notepad ++的方式不同

jsFiddle: http://jsfiddle.net/renavi/ATjvt/5/ jsFiddle: http : //jsfiddle.net/renavi/ATjvt/5/

function AddtoCart() {
  console.log('hi');
  var x = document.getElementById('Items');
  var new_row = x.rows[1].cloneNode(true);
  var len = x.rows.length;
  new_row.cells[0].innerHTML = len;
  var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
  inp1.id += len;
  inp1.value = '';
  var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
  inp2.id += len;
  inp2.value = '';
  x.appendChild(new_row);
}

The direct file is here 直接文件在这里

Pastebin: http://pastebin.com/sutGWjSY 粘贴框: http//pastebin.com/sutGWjSY

You simply need to use simpleCart 您只需要使用simpleCart

It is a free and open-source javascript shopping cart that easily integrates with your current website. 这是一个免费的开源javascript 购物车 ,可轻松与您当前的网站集成。

You will get the full source code at github 您将在github上获得完整的源代码。

For a project this size, you should stop writing pure JavaScript and turn to some of the libraries available. 对于如此大小的项目,您应该停止编写纯JavaScript并转向一些可用的库。 I'd recommend jQuery ( http://jquery.com/ ), which allows you to select elements by css-selectors, which I recon should speed up your development quite a bit. 我建议使用jQuery( http://jquery.com/ ),它允许您通过css-selectors选择元素,我认为这将大大加快您的开发速度。

Example of your code then becomes; 然后,您的代码示例变为;

function AddtoCart() {
  var len = $("#Items tr").length, $row, $inp1, $inp2, $cells;

  $row = $("#Items td:first").clone(true);
  $cells = $row.find("td");

  $cells.get(0).html( len );

  $inp1 = $cells.get(1).find("input:first");
  $inp1.attr("id", $inp1.attr("id") + len).val("");

  $inp2 = $cells.get(2).find("input:first");
  $inp2.attr("id", $inp2.attr("id") + len).val("");

  $("#Items").append($row);
    }

I can see that you might not understand that code yet, but take a look at jQuery, it's easy to learn and will make this development way faster. 我可以看到您可能还不了解该代码,但请看一下jQuery,它很容易学习,可以使这种开发方式更快。

I would use the libraries already created specifically for js shopping carts if I were you though. 如果我是我,我将使用已经专门为js购物车创建的库。

To your problem; 对你的问题; If i look at your jsFiddle, it doesn't even seem like you have defined a table with the id Items? 如果我看一下您的jsFiddle,似乎还没有定义ID为Items的表? Maybe that's why it doesn't work? 也许这就是为什么它不起作用?

I think it is a better idea to start working with a raw data and then translate it to DOM (document object model) 我认为最好先处理原始数据,然后将其转换为DOM(文档对象模型)

I would suggest you to work with array of objects and then output it to the DOM in order to accomplish your task. 我建议您使用对象数组,然后将其输出到DOM以完成任务。

You can see working example of following code at http://www.softxml.com/stackoverflow/shoppingCart.htm 您可以在http://www.softxml.com/stackoverflow/shoppingCart.htm上查看以下代码的工作示例

You can try following approach: 您可以尝试以下方法:

//create array that will hold all ordered products
    var shoppingCart = [];

    //this function manipulates DOM and displays content of our shopping cart
    function displayShoppingCart(){
        var orderedProductsTblBody=document.getElementById("orderedProductsTblBody");
        //ensure we delete all previously added rows from ordered products table
        while(orderedProductsTblBody.rows.length>0) {
            orderedProductsTblBody.deleteRow(0);
        }

        //variable to hold total price of shopping cart
        var cart_total_price=0;
        //iterate over array of objects
        for(var product in shoppingCart){
            //add new row      
            var row=orderedProductsTblBody.insertRow();
            //create three cells for product properties 
            var cellName = row.insertCell(0);
            var cellDescription = row.insertCell(1);
            var cellPrice = row.insertCell(2);
            cellPrice.align="right";
            //fill cells with values from current product object of our array
            cellName.innerHTML = shoppingCart[product].Name;
            cellDescription.innerHTML = shoppingCart[product].Description;
            cellPrice.innerHTML = shoppingCart[product].Price;
            cart_total_price+=shoppingCart[product].Price;
        }
        //fill total cost of our shopping cart 
        document.getElementById("cart_total").innerHTML=cart_total_price;
    }


    function AddtoCart(name,description,price){
       //Below we create JavaScript Object that will hold three properties you have mentioned:    Name,Description and Price
       var singleProduct = {};
       //Fill the product object with data
       singleProduct.Name=name;
       singleProduct.Description=description;
       singleProduct.Price=price;
       //Add newly created product to our shopping cart 
       shoppingCart.push(singleProduct);
       //call display function to show on screen
       displayShoppingCart();

    }  


    //Add some products to our shopping cart via code or you can create a button with onclick event
    //AddtoCart("Table","Big red table",50);
    //AddtoCart("Door","Big yellow door",150);
    //AddtoCart("Car","Ferrari S23",150000);






<table cellpadding="4" cellspacing="4" border="1">
    <tr>
        <td valign="top">
            <table cellpadding="4" cellspacing="4" border="0">
                <thead>
                    <tr>
                        <td colspan="2">
                            Products for sale
                        </td>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>
                            Table
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Table','Big red table',50)"/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Door
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Door','Yellow Door',150)"/>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Car
                        </td>
                        <td>
                            <input type="button" value="Add to cart" onclick="AddtoCart('Ferrari','Ferrari S234',150000)"/>
                        </td>
                    </tr>
                </tbody>

            </table>
        </td>
        <td valign="top">
            <table cellpadding="4" cellspacing="4" border="1" id="orderedProductsTbl">
                <thead>
                    <tr>
                        <td>
                            Name
                        </td>
                        <td>
                            Description
                        </td>
                        <td>
                            Price
                        </td>
                    </tr>
                </thead>
                <tbody id="orderedProductsTblBody">

                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="3" align="right" id="cart_total">

                        </td>
                    </tr>
                </tfoot>
            </table>
        </td>
    </tr>
</table>

Please have a look at following free client-side shopping cart: 请查看以下免费的客户端购物车:

SoftEcart(js) is a Responsive, Handlebars & JSON based, E-Commerce shopping cart written in JavaScript with built-in PayPal integration. SoftEcart(js)是一个使用JavaScript编写,内置PayPal集成的基于响应,手把和JSON的电子商务购物车。

Documentation 文献资料

http://www.softxml.com/softecartjs-demo/documentation/SoftecartJS_free.html http://www.softxml.com/softecartjs-demo/documentation/SoftecartJS_free.html

Hope you will find it useful. 希望您会发现它有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM