【问题标题】:jQuery Loop? Clone? Simply WHY?jQuery循环?克隆?只是为什么?
【发布时间】:2012-11-22 00:38:40
【问题描述】:

新版本(不是新问题...)

所以,我遇到了 .click();.html(); 的“循环”问题。

检索 XML 数据:OK

function afficher(NomPizz, Prix1, Prix2, Prix3) {//HERE IS MY CODE//});

将它们打印到屏幕上:OK

$('#pricecontainer').show(); //Display my container and put values in with .html();
$('#prix1').html('SOLO 1P<p id="p1" style="line-height:10px;">' + Prix1.toFixed(2) + '</p>');
$('#prix2').html('MAXI 2P<p id="p2" style="line-height:10px;">' + Prix2.toFixed(2) + '</p>');
$('#prix3').html('SUPER 4P<p id="p3" style="line-height:10px;">' + Prix3.toFixed(2) + '</p>');​

点击时将值附加到其他 div:OKNOT

一切正常...一次!当我点击更多次时,值“克隆”本身。

所以,如果我点击一次:我添加了 1 个项目。

我得到了:1 OK

点击两次。

我得到了 3,前一个和 另外两个

点击三次。

我得到了 6,前三个和 THRE MORE

等等……等等……

我把这段代码 INTO 我的function afficher(); 我找到的唯一一个解决方案......糟糕的一个!

$("clickedItemId").click(function() {
    var Figure = $(this).find('p').html();
    totalArea.value += '+' + Figure;
    var Screen = totalArea.value.replace(/'/g, ' ');
    var result = eval(Screen);
    totalArea.value = result;
    var $newItem = "<span style='float:left'>1 " + NomPizz.toUpperCase() + "</span><span style='float:right'>" + Figure + "</span><br/>";
    $('<div><div>').html($newItem).appendTo(RecapTick);
    Display2.value = "TOTAL (EUR): " + totalArea.value;
    $('#pricecontainer').hide();
});​

所以,我的function afficher(); 的整个代码将是:

function afficher(NomPizz, Prix1, Prix2, Prix3) {
    var totalArea = document.getElementById('totalArea');
    var Display2 = document.getElementById('Display2');
    var RecapTick = document.getElementById('MidTiTx');
    $('#pricecontainer').show();
    $('#prix1').html('SOLO 1P<p id="p1" style="line-height:10px;">' + Prix1.toFixed(2) + '</p>');
    $('#prix2').html('MAXI 2P<p id="p2" style="line-height:10px;">' + Prix2.toFixed(2) + '</p>');
    $('#prix3').html('SUPER 4P<p id="p3" style="line-height:10px;">' + Prix3.toFixed(2) + '</p>');
    //BUG HERRERRERERERERER
    $("clickedItemId").click(function() {
        var Figure = $(this).find('p').html();
        totalArea.value += '+' + Figure;
        var Screen = totalArea.value.replace(/'/g, ' ');
        var result = eval(Screen);
        totalArea.value = result;
        var $newItem = "<span style='float:left'>1 " + NomPizz.toUpperCase() + "</span><span style='float:right'>" + Figure + "</span><br/>";
        $('<div><div>').html($newItem).appendTo(RecapTick);
        Display2.value = "TOTAL (EUR): " + totalArea.value;
        $('#pricecontainer').hide();
    });
};​


PS 我住在这里是旧版本的帖子(与其他代码相同的 pb):

所以,我的问题如下:

[现场演示][1]

编辑: [下载源][2]

这是一个简单的购物车,可以从 xml 中检索产品列表 文件。 这部分有效!

当它们被点击时,产品被添加到下面的列表中,但是当 你重复点击同一个,总这些应该添加 ... 这就是我卡住的地方!

我尝试更改第 62 行:

tot = parseInt(jQuery(this).find('.prow').html());

收件人:

tot = parseInt(jQuery(this).find('.prow').html()+1);

但不工作......我认为问题在于我正在使用。 .click();onclick="" 方法 ???或者可能是因为“var”使用不当?

请高人指教!

这是我的 jsCode:

function calculate(){
  var tot = 0;
  jQuery(".totprice").each(function(e,b){
      tot += parseInt(jQuery(this).text());
  });
  return jQuery("#amt").html("$"+tot);
}

function showprod(){
  jQuery(".prod").each(function(e){
      jQuery(this).delay(500*e).fadeIn('fast');
  });
}

function clearcart(){
  jQuery("#clear").live('click',function(){
      jQuery(".tetew").fadeIn(4000,function(){
          jQuery(this).remove();
          calculate();
      });
  });
}

function delete_ajax(){
  jQuery(".del").live('click',function(e){
      var a = jQuery(this);
      var p = a.parent().parent().parent().parent().parent();
      if(p){
          p.fadeOut('slow',function(){
              jQuery(this).remove();
              calculate();
          });
      }
  });
}

function addtocart(){
jQuery(".addtocart").click(function(e){
      var getprod = jQuery(this).attr("prodid");
      var getval  = jQuery(this).attr("prodval");

      jQuery("#msg").fadeIn('slow');

      jQuery.ajax({
          type:'GET',
          url:'db.xml',
          dataType:'xml',
          success: function(xml){
              jQuery(xml).find('databases').each(function(){
                  jQuery(this).find('prod').each(function(e){
                  var db_id = jQuery(this).attr('id');

                  jQuery("#msg").fadeOut('slow');
                      if(getprod == db_id){
                          var cookies = 1;
                          jQuery(".tetew").each(function(){
                              var _this = jQuery(this);
                              var _store = _this.find('.pstore');
                              var ident = _this.find('.pqty');

                              if(getprod == ident.text()){
                                  var tot = parseInt(jQuery(this).find('.prow').html()); //Put a +1 here won't work...
                                  jQuery(this).find('.prow').html(tot);
                                      var restot = parseInt(jQuery(this).find('.prow').text()) * parseInt(jQuery(this).find('.price').text());
                                      jQuery(this).find('.totprice').html(restot);
                                  cookies = 0;
                                  return false;
                              }else{
                                  cookies = 1;
                              }
                          });

                          if(cookies == 1){

                          var results = "<div class='tetew'>";
                              results +="<table>";
                              results +="<tr>";
                              results +="<td class='pqty' style='display:none' valign='top'>" + jQuery(this).attr("id") + "</td>";
                              results +="<td class='img' valign='top'><img src='" + jQuery(this).attr('img') + "' width='40' height='40' /></td>";
                              results +="<td class='pstore' valign='top'>" + jQuery(this).text() + "</td>";               
                              results +="<td class='prow' valign='top'>1</td>";                           
                              results +="<td class='price' valign='top'>" + jQuery(this).attr('price') + "</td>";                     
                              results +="<td class='totprice' valign='top'>" + jQuery(this).attr('price') + "</td>";
                              results +="<td  valign='top'><a href='javascript:void(0)' class='del'>Delete</a></td>";
                              results +="</tr>";
                              results +="</table>";
                              results +="</div>";
                          }

                          jQuery(".tetew:eq("+e+")").hide().fadeIn('fast');
                              jQuery("#addto").append(results);
                              calculate();
                          return false;
                      }
                  });

              }); 
          }
      });

  });
}

 function loadXMLdb() {
        $.ajax({
            type: "GET",
            url: "db.xml",
            dataType: "xml",
            success: function(xml) {
                $(xml).find('prod').each(function() {
                    var _Nom = jQuery(this).text();
                    var Col1 = jQuery(this).attr('id');
                    var Col2 = jQuery(this).attr('price');
                    var Col3 = $(this).find('grand').text();
                    $('<div class="prod" style="display:block;" onclick="addtocart();"></div>').html(_Nom + '<br /><img

src="images/pizza.png">
Ajouter').appendTo(".vprod");

                });
            }
        });

    }

jQuery(document).ready(function(){    
  showprod();
  clearcart();
  addtocart();    
  delete_ajax();
loadXMLdb();
});

[1]:http://bzez.0fees.net/examples/jCart/[2]: http://bzez.0fees.net/examples/jCart/jCart.zip

【问题讨论】:

  • 嗨,bZezz,我会看看你的代码并尽力帮助你。我还建议你少写,多做 :) 当你的 js 代码开始增长太多时,你有时会感到有点困惑。
  • 嗨! 1、谢谢!第二,我会尽量少写多做;)
  • 谢谢,不需要拉上拉链。我已经在本地获取了文件。检查一下

标签: xml jquery auto-increment xml-database


【解决方案1】:

您的购物车似乎只会反映 xml 文件中的内容,因此您的每个商品中只能包含 1 个。我建议您以不同的方式看待您的问题。

试试这样的:

var cart = [];

var items = [
    {id:1, price:100, name:"Catch Arena"},
    {id:2, price:400, name:"Pepperonni"},
    {id:3, price:1400, name:"Fruits de Mer"},
    {id:4, price:1400, name:"Chickenita"},
];

然后,将商品添加到购物车:

<a href="#" onclick="addToCart(0);">Add Catch Arena</a>
<a href="#" onclick="addToCart(1);">Add Pepperonni</a>
<a href="#" onclick="addToCart(2);">Add Fruits de Mer</a>
<a href="#" onclick="addToCart(3);">Add Chickenita</a>

我在这里得到的 addToCart 使用数组的索引(从零开始):

window.addToCart = function(idx) {
    cart.push(items[idx]);
    displayCart();
};

现在你有了一个购物车,你需要展示它:

<div id="ShoppingCart">Your cart is empty</div>
<div id="total"></div>
...
window.displayCart = function() {
    var cartHtml = [];
    var cartTotal = 0;
    for (i=0; i<cart.length; i++) {
        cartHtml.push("<div>" + cart[i].name + ", " + cart[i].price + "</div>");
        cartTotal += cart[i].price;
    }
    $('#total').html(cartTotal);
    $('#ShoppingCart').html(cartHtml.join(''));
};

我已经在 jsfiddle 中运行了这个:http://jsfiddle.net/R4rzC/

我也不会说这是最佳实践,因为购物车可能应该与后端数据库等同步,但我敢说你实现购物车是 js 的原因,可能是出于技术原因!

【讨论】:

  • 不错的一个!但是,我需要 XML 数据库...您的代码可以从 xml 文件中获取项目 ID 吗?而且,我们可以添加“价格”值的数量吗?对不起,我是初学者!
  • 当我想获得总金额时,我遇到了同样的问题...jsfiddle.net/bZezzz/acUvL
  • 我对总代码做了一个小修改,试试这个小提琴:jsfiddle.net/h6eFf
【解决方案2】:

我想建议重新编写 javascript 代码。 (有时这确实会帮助您获得更清晰的解决方案)


在这种状态下,它非常混乱且难以阅读/调试。 这样以后你可能会遇到更多的错误。

当我在本地重新创建并尝试循环时,它循环不止一次。 而且您还没有充分利用 jQuery SELECTOR,请查一下 http://api.jquery.com/category/selectors/

今晚回家后我会回答您的问题,并提供更多解决方案。 同时,如果可以的话,尝试重写它

尝试这样做。将 product_ids 放入 TR

var obj = $('#table tr#prod_id_2').find('.prow');

var new_qty = obj.html() * 1; //gets current qty
new_qty = new_qty + 1;

obj.html( new_qty );

【讨论】:

  • 你好,你有机会重写它吗?有时如果代码变得混乱,我们需要重写代码。
【解决方案3】:

所以,睡了几个小时后,我找到了解决办法。

我创建了一个新的function poster();,它检索点击的元素信息并由onclick="poster(NomPizz, Prix)" 调用。

这是有效的新代码:

如果有人有更好的想法,我会接受!

function afficher(NomPizz, Prix1, Prix2, Prix3) {
            var totalArea = document.getElementById('totalArea');
            var Display2 = document.getElementById('Display2');
            $('#pricecontainer').show();   \\Added <div> above
            $('#prix1').html('<div onclick="poster(\''+NomPizz+'\','+Prix1+')">SOLO 1P '+Prix1.toFixed(2)+'</div>');
            $('#prix2').html('<div onclick="poster(\''+NomPizz+'\','+Prix2+')">MAXI 2P '+Prix2.toFixed(2)+'</div>');
            $('#prix3').html('<div onclick="poster(\''+NomPizz+'\','+Prix3+')">SUPER 4P '+Prix3.toFixed(2)+'</div>');
            };

//NEW FUNCTION
function poster(NomPizz, Prix) {
            var RecapTick = document.getElementById('MidTiTx');
            totalArea.value += '+'+ Prix;
            var Screen = totalArea.value.replace(/'/g, ' ');
            var result = eval(Screen);
            totalArea.value = result.toFixed(2);
            var $newItem = "<span style='float:left'>1 " + NomPizz.toUpperCase() + "</span><span style='float:right'>" + Prix.toFixed(2)+"</span><br/>";
            $('<div><div>').html($newItem).appendTo(RecapTick);
            Display2.value = "TOTAL (EUR): "+totalArea.value;
            $('#pricecontainer').hide();
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 2019-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-22
    相关资源
    最近更新 更多