如何获取点击事件的来源

How to get the source of the click event

使用 jQuery,我在一个 div 中生成了一些按钮。

一个按钮如下所示:

<button type="button" value="A_DIFFERENT_VALUE_EACH_TIME" class="col-md-4 text-center btn btn-default btn-lg" >
  <h3>A_DIFFERENT_TEXT_EACH_TIME</h3>
</button>

我喜欢其中的 10 个,一首 div。我需要的是一个事件处理程序,它给我单击按钮的 value

到目前为止,我已经完成了以下工作:

$("#card-subcontainer button").click(function(event){handleCardChoosed(event.target);})

但它不起作用,因为event.target可能是h3button。我怎样才能始终获得我们注册了点击事件的元素(而不是像目前获得焦点的元素?

您的绑定在按钮 $("#card-subcontainer button") 上,因此 this 上下文应该是对单击按钮的引用。

$("#card-subcontainer button").click(function() {
  console.log(this); // this is the reference to the clicked button element
  console.log(this.value); // use this to access the value of the button
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="card-subcontainer">
  <button type="button" value="1" class="col-md-4 text-center btn btn-default btn-lg">
    <h3>1st</h3>
  </button>
  <button type="button" value="2" class="col-md-4 text-center btn btn-default btn-lg">
    <h3>2nd</h3>
  </button>
  <button type="button" value="3" class="col-md-4 text-center btn btn-default btn-lg">
    <h3>3rd</h3>
  </button>
  <button type="button" value="4" class="col-md-4 text-center btn btn-default btn-lg">
    <h3>4th</h3>
  </button>
</div>