单击按钮组时如何识别单击了哪个按钮

时间:2019-03-19 06:30:09

标签: javascript jquery

我有一个由四个按钮组成的按钮组,我想做的就是每当用户单击我要提取其文本的任何按钮时

  • 我正在做这样的事情

$(".btn").click(function() {
  var button_text = $('#oneMonth').text();
  alert(button_text)
})
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>
<div class="btn-group" role="group" align="center">

  <button type="button" class="btn btn-primary" id="sevenDays">Seven Days</button>
  <button type="button" class="btn btn-primary" id="oneMonth">One Month</button>
  <button type="button" class="btn btn-primary" id="sixMonths">Six Months</button>
  <button type="button" class="btn btn-primary" id="oneYear">One Year</button>
</div>

我正在做这样的事情,但这不是正确的方法,因为我必须放置每个按钮的ID才能获取文本

如果用户单击任何按钮,我只想获得该按钮的文字

2 个答案:

答案 0 :(得分:0)

在警报中使用this关键字而不是特定的选择器来获取被单击按钮的文本

var button_text = $(this).text();

这将始终给出ID为oneMonth的按钮文本

$('#oneMonth').text();

$(".btn").click(function() {
  var button_text = $(this).text();
  alert(button_text)
})
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>
<div class="btn-group" role="group" align="center">

  <button type="button" class="btn btn-primary" id="sevenDays">Seven Days</button>
  <button type="button" class="btn btn-primary" id="oneMonth">One Month</button>
  <button type="button" class="btn btn-primary" id="sixMonths">Six Months</button>
  <button type="button" class="btn btn-primary" id="oneYear">One Year</button>
</div>

答案 1 :(得分:0)

您可以通过将此jQuery添加到您的代码中来实现。这是一个有效的代码段:

var buttons = $("button");
buttons.click(function() {
  $(".display__text").text($(this).text());
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>
<div class="btn-group" role="group" align="center">

  <button type="button" class="btn btn-primary" id="sevenDays">Seven Days</button>
  <button type="button" class="btn btn-primary" id="oneMonth">One Month</button>
  <button type="button" class="btn btn-primary" id="sixMonths">Six Months</button>
  <button type="button" class="btn btn-primary" id="oneYear">One Year</button>
</div>

<div class="display__text"></div>