1

基本上我正在尝试在 div 内的购物车中显示产品。购物车托管在其他地方,为了检索产品,我发出了一个 getJSON 请求,该请求返回一个 json 对象,如下所示:

{
"products":[
    {
        "id": "3045365",
        "name": "Test Product",
        "code": "foo123",
        "image": "",
        "url": "",
        "length": "0",
        "width": "0",
        "height": "0",
        "options": {"color":"red"},
        "quantity": 1,
        "price_each": 10,
        "price": 10,
        "weight_each": 1,
        "weight": 1,
        "shipto": "",
        "category": "DEFAULT",
        "sub_frequency": "",
        "sub_startdate": "0000-00-00",
        "sub_nextdate": "0000-00-00",
        "sub_enddate": "0000-00-00"
    },
    {
        "id": "3045366",
        "name": "Second Product",
        "code": "bar456",
        "image": "",
        "url": "",
        "length": "0",
        "width": "0",
        "height": "0",
        "options": {},
        "quantity": 1,
        "price_each": 100,
        "price": 100,
        "weight_each": 1,
        "weight": 1,
        "shipto": "",
        "category": "DEFAULT",
        "sub_frequency": "",
        "sub_startdate": "0000-00-00",
        "sub_nextdate": "0000-00-00",
        "sub_enddate": "0000-00-00"
    },
    {
        "id": "3045367",
        "name": "Example Subscription",
        "code": "xyz456",
        "image": "",
        "url": "",
        "length": "0",
        "width": "0",
        "height": "0",
        "options": {"color":"red"},
        "quantity": 1,
        "price_each": 6,
        "price": 6,
        "weight_each": 4,
        "weight": 4,
        "shipto": "",
        "category": "DEFAULT",
        "sub_frequency": "1m",
        "sub_startdate": "2010-10-15",
        "sub_nextdate": "2010-11-15",
        "sub_enddate": "2013-01-01"
    }
],
"product_count": 3,
"total_item_price": 116,
"total_discount": -5,
"total_price": 111,
"total_weight": 6,
"session_id": "9bpdjvm2ju0bulm6d7kkcf6d31",
"coupons":{
    "test2":{
        "id":"201",
        "name":"test for line item coupon discount",
        "discount":-5}
},
"custom_fields":{
    "my_hidden_value":"I'm hidden!",
    "example_hidden":"value_1"
},
"messages":{
    "errors":[],
    "warnings":[],
    "info":[]
}
}

我当前的代码,当用户点击添加到购物车时,检查 div 是否为空。如果是,它会从 json 对象中添加第一个产品。

如果 div 不为空,则它将 div 中的第一个产品的名称与 json 对象中的第一个元素的名称进行比较。如果结果为真,则只更新价格而不更新名称。如果结果为假,则检查 json 对象中的下一个元素。这是我的代码:

$(document).ready(function()
{

var x=0;
var y=0;

$("#addCart").click(function()
{

    if($('#cartContent').is(':empty'))
    {
        $.getJSON('https://'+storedomain+'/cart?'+fcc.session_get()+'&output=json&callback=?', function(data) 
        {
            $('#cartContent').append('<p class="name">' + data.products[x].name + '</p>' + '<p class="price">' + data.products[x].price + '</p>');      
        });
    }
    else 
    {
    $.getJSON('https://'+storedomain+'/cart?'+fcc.session_get()+'&output=json&callback=?', function(data) 
    {
            $('.name').each(function()
            {   
                while (y < data.products.length-1)
                {   
                    if($(this).text() === data.products[x].name)
                    {   
                        $('.price').eq(x).text(data.products[x].price);     
                    }   
                    x++;
                    y++;
                }
                x=0;
                y=0;
            });
            });
    }               
});
});

<a id="addCart" href="http://mydomain.foxycart.com/cart?name=test-clothes&price=10.00">Add to Cart</a>
<div id="cartContent" style="display: inline; clear: both;"></div>

这一切都很好。我的问题是我已经测试了好几天,但我想不出一种方法可以:

  1. 如果用户将产品 1 添加到购物车,则附加名称 + 价格
  2. 如果用户将相同的产品 1 添加到购物车,只更新价格
  3. 如果用户将产品 2 添加到购物车,则附加名称 + 价格
  4. 如果用户将相同的产品 2 添加到购物车,只更新价格

到目前为止,我的代码只设法附加和比较一个产品。不是连续的。我还是 javascript 的新手,如果我的方法很荒谬,请帮我提出一个更好的方法。

谢谢!

4

3 回答 3

0

您可以使用一个对象(类似于其他编程语言中的 HashMap 或关联数组)来存储当前购物车状态并在检查此对象后对未来的点击采取行动。您还需要跟踪当前的产品数量,因为这不是 JavaScript 对象提供的。这取决于您将存储的值

//初始为空,或者你可以将其初始化为已保存的购物车状态。var cartProducts = {}, numProducts = 0;

$("#addCart").click(function () {

if (numProducts === 0) {
    //Here, create the DOM fragment representing your product.
    cartProducts["product-id"] = $("<div"); 

    numProducts += 1;

} else if(cartProducts["product-id"]) {
    //Update the product price since it has already been added to the DOM.

//When refactoring, combine this else statement with the first if condition.
} else {
    //At this point you know that the product has not been previously add it,
    //and can go ahead and add it to the DOM.

    //...
    numProducts += 1;        
}

});

只是对您的代码结构的一般评论:

  1. 评论您的代码将有助于其他人和您将来理解您的代码。
  2. 尝试将您的代码模块化为负责一小块代码的单独函数。这将有助于代码的可管理性、可重用性和可测试性。
  3. 如果要迭代 [i->n; 则使用 for 循环而不是 while 循环 我++]。
  4. JSLint您的代码以帮助您设置样式和正确的语法。

希望这可以帮助你!

于 2013-01-31T19:33:53.237 回答
0

也许您需要映射您添加到购物车的产品及其价格。

前任:

<div class="product">
    Prod 1 
    <div class="product-price">100</div>
</div>

<script>
    var productNames = [];

    function checkExisting(name) {
        return !(productNames.indexOf(name) < 0);
    }

    function appendProduct(name, price) {
        var p = $('<div>' + name + '<div>' + price + '</div></div>');
        p.data('name', name);
    }

    $(addToCart).click(function() {
        var products = $('.product');

        products.each(function() {
            if( checkExisting($(this).data('name')) ) {
                productNames.push($(this).data('name'));
            }
        });

        $.getJSON(bla, function(data) {
            for(var i = 0; i < data.products.length; i++) {
                 if(checkExisting(data.products[i].name)) {
                     appendProduct();
                 }
                 else {
                     updatePrice();
                 }
            }
        });
    });
</script>

或类似的东西。

于 2013-01-31T19:29:44.527 回答
0

下面的代码是我的做法:

    //occurs when the element with id addCart is clicked
$("#addCart").click(function()
{
    //gets json of products
    $.getJSON('https://'+storedomain+'/cart?'+fcc.session_get()+'&output=json&callback=?', function(data) 
    {
        //creates arrays to hold values
        var items = new Array();
        var names = new Array();
        var price = new Array();

        //foreach product in data name it item and do the following
        data.products.each(function(item){
            //See if the item id is in the items array
            var index = $.inArray(item.id, items);
            //If it isn't
            if(index == -1)
            {
                //Add the item to the arrays
                items.push(item.id);
                names.push(item.name);
                price.push(item.price);
            }
            //it already is in the array one time so just add to price
            else
            {
                //add to the price by the amount of the item price
                price[index] += item.price;
            }
        });

        //empty the html from the element with id cartContent 
        $('#cartContent').empty();
        //loop through all items in item array
        for (var i = 0; i < items.length ; i++) {
            //Add html for each item since we only added each once this happens once per item
            $('#cartContent').append('<p class="name">' + names[i] + '</p>' + '<p class="price">' + price[i] + '</p>');
        }
    });
});
于 2013-01-31T19:41:38.850 回答