How to get to a child of a parent when multiple exist?
There is problem with the following code. I am trying to Increase the dollar amount for all the numbers independently (by 0.01 per click). But it only seems to work on the first "content" class, not on the other 2. Each of these are identical besides the amount.
Layout:
<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">
<开发者_如何学Godiv class="item"><span class="number">$3.45</span><a href="#" class="incNumber"> Increase</a></div>
</div>
Script:
$(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;
});
});
This script seems to function fine. converting it to a float and then back seems to increase it by 0.01 however this is not intentional...
For me, your code works without any unexpected behavior... it does nothing. But when I change this
amount = parseFloat(amount) + 0.01;
The increase button increases the individual numbers by 0.01
From the jQuery documentation you can find this:
In an HTML document, we can use .html() to get the contents of any element. If the selector expression matches more than one element, only the first one's HTML content is returned.
http://api.jquery.com/html/
You might use each to iterate over all elements found...
I think you missed the incrementing. but anyways this is a modified version of ur code. I hope I got what you are trying to do.
$(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;
});
});
精彩评论