[英]How to get to a child of a parent when multiple exist?
以下代碼有問題。 我試圖單獨增加所有數字的美元金額(每次點擊增加0.01)。 但是它似乎只適用於第一個“內容”類,而不適用於其他兩個類。除數量外,每個類都是相同的。
布局:
<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,但這不是故意的...
從jQuery文檔中,您可以找到以下內容:
在HTML文檔中,我們可以使用.html()獲取任何元素的內容。 如果選擇器表達式匹配多個元素,則僅返回第一個的HTML內容。
您可能會使用每個元素來迭代找到的所有元素...
對我來說,您的代碼可以正常工作,沒有任何意外的行為……它什么也沒做。 但是當我改變這個
amount = parseFloat(amount) + 0.01;
增加按鈕將單個數字增加0.01
我想你錯過了增加。 但無論如何,這是ur代碼的修改版本。 我希望我能得到你想要做的。
$(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;
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.