简体   繁体   English

使用Javascript计算产品总和

[英]Calculating sum of products using Javascript

I have list of products for users to select.我有产品列表供用户选择。 When user selects a product, the price is displayed and the user enters the quantity to calculate the total price for all selected products.当用户选择产品时,会显示价格,用户输入数量以计算所有选定产品的总价。

Now with my code, the total price for the first selected product appears the same for all other products selected afterwards.现在使用我的代码,对于之后选择的所有其他产品,第一个选定产品的总价看起来相同。 ie IE

If user selects Fifa and PRO the total price for FIFA appears for PRO as below如果用户选择Fifa and PRO ,则 FIFA 的总价为 PRO 显示如下

Item : Fifa    
Price : 100eu    
Quantity : 4    
Total price : 400eu  

Item : PRO     
Price: 50eu    
Quantity: 1    
Total Price: 400eu

But this is what i am looking to have但这就是我想要的

Item : Fifa            
Price : 100eu            
Quantity : 4            
Total price : 400eu          

Item : PRO             
Price: 50eu            
Quantity: 1            
Total Price: 50eu

Total Order Price = 400eu + 50eu = 450eu

JS JS

public selectGame(game){
     $(".gameshop").append(
            '<p id="name">Item: ' + game.name + '</p>'+
            '<p name="price" id="price" data-price="'+game.price+'"> Price  :  ' + game.price + '</p>'+
            '<input type="text"  onKeyUp="final()" id="quantity"  name="quantity" />' +
            '<p id="final_price">Total Price  $:<span></span></p>').appendTo('form')    
}

function final()
{        
    a = Number($('#quantity').val());
    b = Number($('#price').data("price"));
    c = a * b;

    $("#final_price span").text(c);    
}

HTML HTML

        <form class="form-horizontal" method="post">
    @foreach ($errors->all() as $error)
    <p class="alert alert-danger">{{ $error }}</p>
    @endforeach
    @if (session('status'))
    <div class="alert alert-success">
            {{ session('status') }}
        </div>
    @endif
    {!! csrf_field() !!}
    <fieldset>

    <div class="panel label_container">
<input onclick="return selectGame(this)" type="checkbox" id="{!! $game->id !!}" " /> 
   <label class="mylabel" >  </label>

</div>
    <legend>Games</legend> 

    <div class="gameshop" id="gameshop">



    </div>


            </div>
        </fieldset>
    </form>

Update更新

 function selectGame(game)
{

    $('.gameshop').append(
        '<div class="item">'+
        '<p class="name"> Item: ' + game.name + '</p>'+
        '<p class="price"   data-price="'+game.price+'"> Price  :  ' + game.price + '</p>'+
        '<input type="text"   class="quantity" name="quantity" />'+
        '<p class="total">Total Price  $:<span></span></p>'+
         '</div>'

    )

    $('.gameshop').on('keyup','.quantity',function()

       {

        var a = Number($(this).val());
        var b = Number($(this).closest('div').find('.price').data('price'));

        alert(b);



       });

}

You are appending dynamically tags with same ids, consider adding something to the id such您正在动态添加具有相同 ID 的标签,请考虑向 id 添加一些内容,例如

id="xxx"+"_"+i 

being i an index我是一个索引

There are a few steps to correct this, since there are a couple of simultaneous problems.有几个步骤可以纠正这个问题,因为同时存在几个问题。 Namely (1) you're re-using id values in your HTML and (2) you're trying to get and update values globally on the page when you want to get do so relatively to the element invoking the event.即(1)您在 HTML 中重新使用id值,以及(2)当您想要对于调用事件的元素执行此操作时,您尝试在页面上全局获取和更新值。

First, replace all of your id s in your dynamic HTML string with class values instead.首先,将动态 HTML 字符串中的所有id替换为class值。 This will prevent the HTML from being invalid by re-using id values.这将通过重复使用id值来防止 HTML 无效。 Something like:就像是:

'<p class="name">Item: ' + game.name + '</p>'+
//... and so on

Also, remove your onKeyUp inline handler from the <input> element:此外,从<input>元素中删除您的onKeyUp内联处理程序:

'<input type="text" class="quantity" name="quantity" />'+

Next, bind your keyup event using jQuery and event delegation.接下来,使用 jQuery 和事件委托绑定您的keyup事件。 Have a single declared event handler on a parent element to handle the event:在父元素上有一个声明的事件处理程序来处理事件:

$('.gameshop').on('keyup', '.quantity', function () {
    //...
});

This event handler replaces your final() function.此事件处理程序替换您的final()函数。 This should take care of the multiple- id problem, but now inside this event handler we need to navigate the DOM to find the elements you're looking for.这应该可以解决多重id问题,但现在在这个事件处理程序中,我们需要导航 DOM 以找到您正在寻找的元素。

First, wrap your dynamic elements in a container of some sort.首先,将您的动态元素包装在某种容器中。 Any <div> will do.任何<div>都可以。 Something like:就像是:

'<div class="product">'+    // <--- here
'<p class="name">Item: ' + game.name + '</p>'+
//...
'<p class="final_price">Total Price  $:<span></span></p>'+
'</div>'    // <--- and here

Then we can use that container as a stopping point to navigate up and down the DOM to find the target elements.然后我们可以使用该容器作为停止点在 DOM 中上下导航以找到目标元素。 First, we can find the "quantity" from the event-throwing element itself.首先,我们可以从事件抛出元素本身中找到“数量”。 So instead of this:所以而不是这个:

a = Number($('#quantity').val());

We can just use the element itself:我们可以只使用元素本身:

var a = Number($(this).val());

For other values, it's a neighboring element.对于其他值,它是一个相邻元素。 This would involve navigating up and down the DOM to find that element.这将涉及在 DOM 中上下导航以找到该元素。 So instead of this:所以而不是这个:

b = Number($('#price').data("price"));

You can do something like this:你可以这样做:

var b = Number($(this).closest('div').find('.price').data('price'));

Notice how it starts from the element throwing the event ( this ), navigates up to the container ( <div> ), then back down to the target element ( .price ).注意它是如何从.price事件的元素 ( this ) 开始,向上导航到容器 ( <div> ),然后返回到目标元素 ( .price )。 This should identify the specific element you want to find, relative to the one throwing the event.这应该标识您要查找的特定元素,相对于引发事件的元素。

Repeat these same corrections for your other elements, selectors, etc.对其他元素、选择器等重复这些相同的更正。

There could very well be other issues here, but these appear to be the main structural/logical problems you're encountering.这里很可能还有其他问题,但这些似乎是您遇到的主要结构/逻辑问题。 (Another potential problem could be that strange combined use of .append() and .appendTo() , I'm not really sure what that's accomplishing. You should only need one of those.) (另一个潜在的问题可能是.append().appendTo()奇怪组合使用,我不太确定这会完成什么。你应该只需要其中一个。)

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

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