点击元素时获取子元素文本并传入输入框的问题解决(jQuery/原生JavaScript)
Hey there! I see the issue here—let's get it sorted quickly.
The Problem
When you use $(".hero-text").text() inside your click handler, you're grabbing the text content of all elements with the hero-text class (which concatenates "10204080") instead of just the one inside the clicked .btn-amount div. That's why every click inserts all values at once.
Fixed JavaScript Code
Here's the corrected version that targets only the clicked div's value:
$(".btn-amount").each(function() { $(this).click(function() { // Use $(this) to reference the clicked .btn-amount, then find its child hero-text var btnCreditsAmount = $(this).find(".hero-text").text(); $('#amountInput').val(btnCreditsAmount); }); });
Even Simplified Version
You can actually skip the .each() loop entirely since jQuery binds events to all matched elements automatically:
$(".btn-amount").click(function() { var btnCreditsAmount = $(this).find(".hero-text").text(); $('#amountInput').val(btnCreditsAmount); });
Full Working Code Example
Here's the complete code to test:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" /> <div class="btn-amount"> <div class="hero-text">10</div> </div> <div class="btn-amount"> <div class="hero-text">20</div> </div> <div class="btn-amount"> <div class="hero-text">40</div> </div> <div class="btn-amount"> <div class="hero-text">80</div> </div> <div class="form-group"> <input type="number" id="amountInput" class="input-field" placeholder="Amount of credits"> </div> <script> $(".btn-amount").click(function() { var btnCreditsAmount = $(this).find(".hero-text").text(); $('#amountInput').val(btnCreditsAmount); }); </script> <style> .btn-amount { min-width: 80px; text-align: center; padding: 0.5rem; border: 1px solid #ccc; float: left; margin: 5px; border-radius: 6px; cursor: pointer; font-weight: bold; background: #f2f4f8; } .form-group { display: block; clear: both; width: 360px; overflow: hidden; position: relative; } .input-field { width: 100%; } </style>
How It Works
$(this)inside the click handler refers directly to the.btn-amountdiv that was clicked..find(".hero-text")narrows down to only thehero-textelement inside that clicked div, so we get the correct single value.- We then set the input's value to that specific text.
内容的提问来源于stack exchange,提问作者Designer
相关产品推荐
相关产品推荐

