Javascript 如何在jQuery中存储单击按钮事件的值

Javascript 如何在jQuery中存储单击按钮事件的值,javascript,jquery,html,Javascript,Jquery,Html,我有一个我创建的按钮列表: <button> red </button> <button> blue </button> <button> yellow </button> 用于获取文本,如图所示 $('button').on('click', function() { var colour = $.trim( $(this).html() ); alert("You have chosen " + c

我有一个我创建的按钮列表:

<button> red </button>
<button> blue </button>
<button> yellow </button>
用于获取文本,如图所示

$('button').on('click', function() {
    var colour = $.trim( $(this).html() );  
    alert("You have chosen " + colour);
});
演示::

也可以使用value属性

<button value="red"> red </button>
<button value="blue"> blue </button>
<button value="yellow"> yellow </button>

$('button').on('click', function() {

  alert("You have chosen "+$(this).text().trim()+" "+ $(this).val()+ " " + $(this).attr('value'));

});

检查演示:

您可以使用html从Button输入值,并检查

$('button').on('click', function() {

  // $(this) gives you the object where the click event occured

  alert("You have chosen " + $(this).text().trim());
});
<button value="red"> red </button>
<button value="blue"> blue </button>
<button value="yellow"> yellow </button>

$('button').on('click', function() {

  alert("You have chosen "+$(this).text().trim()+" "+ $(this).val()+ " " + $(this).attr('value'));

});