簡體   English   中英

如何最接近jquery?

[英]How can I apply closest to jquery?

我希望能夠分別(分別)計算第1節,第2節和第3節。

在此來源中,僅計算了第1節,但第2節和第3節無效。

如何分別計算第1節,第2節和第3節?

ps:部分的數目可能會改變。

 $(".btn-primary").on( "click", function(event) { var $final = parseFloat($("#final").val()); var $first = parseFloat($("#first").val()); $('#is_nums').text($final - $first); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> Section 1 <h4>A : <input type="text" name="final" id="final" value=""> <h4>B : <input type="text" name="first" id="first" value=""> <button class="btn btn-primary" name="calc">confirm</button> <b>calc</b> : <label id="is_nums"></label></h4> Section 2 <h4>A : <input type="text" name="final" id="final" value=""> <h4>B : <input type="text" name="first" id="first" value=""> <button class="btn btn-primary" name="calc">confirm</button> <b>calc</b> : <label id="is_nums"></label></h4> Section 3 <h4>A : <input type="text" name="final" id="final" value=""> <h4>B : <input type="text" name="first" id="first" value=""> <button class="btn btn-primary" name="calc">confirm</button> <b>calc</b> : <label id="is_nums"></label></h4> 

這都是關於HTML的良好嵌套結構。
如果您以此方式組織HTML代碼,則JS將變得清晰透明,而無需使用.prev()或其他可能在進行少量HTML修改后停止工作的東西。
您不應依賴元素的順序,而應依賴其邏輯結構。

類的命名是根據BEM進行的 ,您可以遵循任何其他准則,沒關系。

 $(".my-section__calc").on("click", function(event) { var $section = $(this).closest(".my-section"); var final = parseFloat($section.find(".my-section__final").val()); var first = parseFloat($section.find(".my-section__first").val()); $section.find(".my-section__result").text(final - first); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <div class="my-section"> <h5>Section 1</h5> A: <input type="number" class="my-section__final" name="final" value="0"><br/> B: <input type="number" class="my-section__first" name="first" value="0"><br/> <button class="my-section__calc">confirm</button><br/> <b>calc</b>: <label class="my-section__result"></label> </div> <div class="my-section"> <h5>Section 2</h5> A: <input type="number" class="my-section__final" name="final" value="0"><br/> B: <input type="number" class="my-section__first" name="first" value="0"><br/> <button class="my-section__calc">confirm</button><br/> <b>calc</b>: <label class="my-section__result"></label> </div> <div class="my-section"> <h5>Section 3</h5> A: <input type="number" class="my-section__final" name="final" value="0"><br/> B: <input type="number" class="my-section__first" name="first" value="0"><br/> <button class="my-section__calc">confirm</button><br/> <b>calc</b>: <label class="my-section__result"></label> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM