多个存在时如何找到父母的孩子?

时间:2010-10-08 08:27:20

标签: javascript jquery

以下代码存在问题。我试图独立增加所有数字的美元金额(每次点击0.01)。但它似乎只适用于第一个“内容”类,而不是另一个类2.除了数量之外,每个类都是相同的。

布局:

<div class="content">
    <div class="item"><span class="number">$10.11</span><a href="#" class="incNumber"> Increase</a></div>
</div>
<div class="content">
   <div class="item"><span class="number">$5.04</span><a href="#" class="incNumber"> Increase</a></div>
</div>
<div class="content">
    <div class="item"><span class="number">$3.45</span><a href="#" class="incNumber"> Increase</a></div>
</div>

脚本:

$(function () {
   $(".incNumber").click(function() {
      brother = $(this).closest('div').children('.number');
      amount = $(brother).html().replace(/[^\d\.]/g, "");
      amount = parseFloat(amount);

      $(brother).html('$'+String(amount.toFixed(2)));
      return false;
   });
});

这个脚本似乎运行正常。把它转换成一个浮点然后回来似乎把它增加0.01然而这不是故意的......

3 个答案:

答案 0 :(得分:0)

从jQuery文档中你可以找到:

  

在HTML文档中,我们可以使用   .html()获取任何内容   元件。如果是选择器表达式   匹配多个元素,仅   第一个HTML 内容是   返回。

http://api.jquery.com/html/

您可以使用每个迭代所有找到的元素......

答案 1 :(得分:0)

对我来说,你的代码没有任何意外行为......它什么都不做。但是当我改变这个

amount = parseFloat(amount) + 0.01;

增加按钮可将个别数字增加0.01

答案 2 :(得分:0)

我认为你错过了增量。但无论如何这是你的代码的修改版本。我希望我得到你想做的事。

$(function () {
    $(".incNumber").click(function() {
    brother = $(this).siblings('.number');
    amount = $(brother).html().replace(/[^\d\.]/g, "");
    amount = parseFloat(amount);
    amount = amount + 0.01;
    $(brother).html('$'+String(amount.toFixed(2)));
        return false;
    });
});
相关问题