JQuery Получить общую цену товара из КАЖДОЙ ячейки и показать, работает, но не правильно - PullRequest
1 голос
/ 08 августа 2011

У меня есть этот javascript, функция jquery, (ниже)

  1. Получает текст внутри каждой ячейки таблицы (класса = "total_item_price") таблицы.
  2. Он помещает его в массив (Prices_array)
  3. Суммирует массив_распределений цен и форматирует их до 2 десятичных знаков.
  4. Затем выводит его в total_order_price или возвращает его, если задано do_request.

Проблема: У меня есть функция, которая удаляет элемент из корзины, а затем вызывает эту функцию (getTotalPrice) для обновления поля цен. Эта часть не работает правильно и не дает правильную цену.

По сути, мне нужна эта функция, чтобы:

  • Получите цену (цены) (.total_item_price), которая находится внутри ячейки.
  • Получить стоимость доставки (.shipping_price) + Добавить их все
  • Показать его внутри ячейки (.total_order_price)

Затем, когда я вызываю свою функцию удаления, я могу вызвать ^ эту ^ функцию, чтобы, надеюсь, правильно обновить цену.
Я также вызываю эту функцию getTotalPrice на DOM Ready, чтобы обновить цены, поэтому важно, чтобы она работала правильно. Она также должна работать, когда я вызываю функцию удаления (ниже).

У меня есть jsfiddle, но он не работает, , но этот код работает на моем локальном хосте. Мне пришлось сжать его для jsfiddle, и он где-то сломался. Не стесняйтесь редактировать, как вы хотите.


Вот код (!): Эта функция получает итоговую цену и отображает ее.
function getTotalPrice(do_request)
{
var prices_array = new Array(); // Where our prices are held 

// For each .total_item_price - a <td> within my table.
$(".total_item_price").each(function(e){
    var text = $(this).text();                   // Get the value
    var prices = text.substring(1, text.length); // Format it into a string
    prices_array.push(prices);                   // Push it onto our array
});

var result = eval(0);
//  Add up our array
for(i = 0; i < prices_array.length; i++)
{
    temp = eval(prices_array[i]);
    result += temp;
}
// Round up our result to 2 Decimal Places
result = Math.round(result*100)/100;
// Output/Return our result
if (do_request == null)
{
    // We want to add our shipping Price and Display the total
    // Get the Shipping Price
    var shipping_price = $(".shipping_price").html();
    shipping_price = shipping_price.substring(1, shipping_price.length);

    // Add em
    result += eval(shipping_price);

    // Round our result to 2 decimal places
    var result=Math.round(result*100)/100;

    // Update & Display the Result
    $('.total_order_price').html("<b>£" + result + "</b>");        
}
else 
{
    // Otherwise we just want the total price and return it.
    return result;
}
}

Это функция, которую я сделал, чтобы удалить строку из таблицы и обновить цены.

// Delete Item from Basket, Run on click of delete button
function delete_item(e)
{
doIt = confirm('Delete Item from Basket?\r\n You can not undo this action.');
if(doIt)
{
  // Get our basket
  var basket_md5 = $(e).parent().find("input[name='basket_md5']").val();
  var url = "<?php echo SERVER_URL."shop/basket"; ?>";
  // Post to basket
  $.post(url, { "do": "delete_item","basket_md5": basket_md5});

  // Delete Row from Table
  // Row Scope
  var row = $(e).parent().parent();

  // Effect & Remove from DOM
  $(row).fadeOut(1000, function(){ 
      $(this).remove();

  });

  // Update the Prices (again)
  //tprice = getTotalPrice("return");
  //$('.total_order_price').html("<b>£" + tprice + "</b>"); 
  getTotalPrice();
 }
} 

1 Ответ

1 голос
/ 08 августа 2011

В function delete_item(e) move 'getTotalPrice ();здесь:

$(row).fadeOut(1000, function(){ 
      $(this).remove();
      // Update the Prices (again)
      //tprice = getTotalPrice("return");
     //$('.total_order_price').html("<b>£" + tprice + "</b>"); 
     getTotalPrice();
  });
...