问题
NEW VERSION (not new problem...)
So, i got a "loop" problem with a .click();
and a .html();
.
Retrieve XML datas: OK
function afficher(NomPizz, Prix1, Prix2, Prix3) {//HERE IS MY CODE//});
Print them to screen: 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>');
Append value to other div when clicked: OK but NOT
Everithing works... ONCE ! When I click more times, the value "clone" itself.
So, if I click one time: 1 Items i added.
I got: 1 OK
Two times click.
I got 3, The previous one and TWO MORE !
Three times click.
I got 6, The three previous and THRE MORE !
Etc... Etc...
I Put this code INTO my function afficher();
The only one solution i've found... BAD one !
$("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();
});
So, the ENTIRE code of my function afficher();
will be:
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 I LIVE HERE THE OLD VERSION OF THE POST (Same pb with other code):
So, my prolem is the following:
[LIVE DEMO][1]
EDIT: [DOWNLOAD SOURCE][2]
It's a simple cart that retrieves the list of products from a xml file. This part works !
When they are clicked, the products added to the list below, but when you click repeatedly on the same, the total of these should be added ... This is where I get stuck !
I tried to change the line 62:
tot = parseInt(jQuery(this).find('.prow').html());
To:
tot = parseInt(jQuery(this).find('.prow').html()+1);
But not working... I think the problem is that I am using. .click(); with onclick="" method ??? Or maybe because of bad "var" use ?
Please someone enlighten me !
Here is my 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
回答1:
it seems that your cart will only reflect what is in the xml file, so you can only have 1 of each item in it. I suggest that you look at your problem differently.
try something like this:
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"},
];
then, add an item to the cart with:
<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>
the addToCart I've got here uses the index (zero based) of the array:
window.addToCart = function(idx) {
cart.push(items[idx]);
displayCart();
};
Now you've got a cart, you need to display it:
<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(''));
};
I've got this running in a jsfiddle: http://jsfiddle.net/R4rzC/
I wouldn't say this is best practice either, as the cart should probably synced with a backend database etc, but I dare say there is a reason why you're implementing a cart is js, probably for technical reasons!
回答2:
I'd like to suggest a re-write of the javascript code. (sometimes this is really going to help you to get a clearer solution)
at this state it is quite confusing and hard to read/debug. You'll probably have more bugs later on this way.
When I recreated locally and tried the loop, it is looping more than once. And you aren't fully taking advantage of jQuery SELECTORs, please look it up http://api.jquery.com/category/selectors/
I'll answer your ques tonight when I get home, and provide some more solution. in the meantime, try to rewrite this if you can
Try to do it like this. putting product_ids in 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:
So, after some sleeping hours I found a solution.
I created a new function poster();
who retrieve clicked element info and called by onclick="poster(NomPizz, Prix)"
.
Here is the working new code:
If someone have better idea i'll take !
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();
};
来源:https://stackoverflow.com/questions/13504315/jquery-loop-clone-simply-why