You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击元素时获取子元素文本并传入输入框的问题解决(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-amount div that was clicked.
  • .find(".hero-text") narrows down to only the hero-text element 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 15:34:11