0

我创建了具有成本属性的图像,例如

 <img src="http://www.macnetwork.org/images/icon_linkedIn.png" cost="280" alt=''/>

在这里,我将在每个成本中添加各种 img 标签。但是当我选择一个 img 时,它的成本必须添加到一个<div>名为.cost

此处为 HTML

 <div id="main">

<img src="http://www.small-icons.com/stock-icons/small-toolbar40.gif" cost="100" alt=''/>
 <img src="http://www.homeworldbusiness.com/media/icons/icon_mini_linkedin.png" cost="200" alt=''/>
 <img src="http://www.driscoll-const.com/images/skin/feed_icon.png" cost="300" alt=''/>
 <img src=" http://www.isos.com/sites/default/files/icon_images/cabling-small.png" cost="400" alt=''/>


 </div>
<div id="secondary">

<img src="http://www.macnetwork.org/images/icon_linkedIn.png" cost="280" alt=''/>
<img src="http://www.macnetwork.org/images/icon_rss.png" cost="140" alt=''/>
<img src="http://www.gogrid.com/gg/images/products/gg_prod_icon.png" cost="80" alt=''/>
<img src="http://www.lateralpaymentsolutions.com/images/contact_small_icon.jpg" cost="20" alt=''/>
 </div> 


 <div id="preview_section" style="clear:both">
 <div class="cost"></div>
<div id="main_img"></div>
  <div id="secondary_img"></div>
 </div>

在这个成本 div 中,我必须添加和减去每个所选图像的值。

如果 选择主 div 中的图像 1和辅助 div 中的图像 2,则成本应为240

同样,当图像更改时,必须降低其先前的成本,并且应该添加所选的图像成本。

我试图更改脚本中的文本

  $(document).ready(function(){
      $("#main img").click(function(){
          var src = $(this).attr('src');
          $("#main_img").css("background-image",'url('+src+')');

          var cost = $(this).attr("cost");
          $(".cost").text(cost);
      });



       $("#secondary img").click(function(){
        var src1 = $(this).attr('src');
        $("#secondary_img").css("background-image",'url('+src1+')');

        var cost = $(this).attr("cost");
       $(".cost").text(cost);
      });


 });

在这种情况下如何使用 jquery 添加或减去值....我做了一个小提琴

4

3 回答 3

2

最简单的方法是存储单独的成本。然后适当更新全局成本变量并重新计算总成本:

cost1 = parseInt($(this).attr("cost"));
var totalCost = cost1 + cost2;
$(".cost").text(totalCost);

注意:您需要parseInt()将成本字符串转换为整数的函数。

注意2:可能还有其他(取决于您的实际要求更好?)方法。例如,您可以使用选择器来查找选定的图像,这样您就不必将成本值存储在(全局)变量中。

请参阅更新的小提琴

于 2013-01-18T10:35:17.840 回答
0

您的错误是因为您使用的是文本并且没有使用任何添加。那么也许使用一个函数来计算成本?

function workOutCost(updatedPrice){
    var newPrice = Math(parseFloat($('.cost').innerHTML)+updatePrice);
    $('.cost').HTML(newPrice);
}
于 2013-01-18T10:37:36.800 回答
0

解析成本并将主要和次要成本存储在单独的变量中。这样,您可以轻松计算一张图像更改时的成本:

$(document).ready(function(){

  var cost1 = 0, cost2 = 0;

  $("#main img").click(function(){
    var src = $(this).attr('src');
    $("#main_img").css("background-image",'url('+src+')');

    cost1 = parseInt($(this).attr("cost"), 10);
    updateCost();
  });

  $("#secondary img").click(function(){
    var src1 = $(this).attr('src');
    $("#secondary_img").css("background-image",'url('+src1+')');

    cost2 = parseInt($(this).attr("cost"), 10);
    updateCost();
  });

  function updateCost(){
    $(".cost").text(cost1 + cost2);
  }

});
于 2013-01-18T10:38:40.613 回答