我有一个我创建的按钮列表:
<button> red </button>
<button> blue </button>
<button> yellow </button>
如何将点击内容的值(让我说我点击红色)存储到我的点击事件中,以便我可以使用我点击事件功能中的值?
$('button').on('click', function() {
var colour = "red";
alert("You have chosen " + colour);
});
答案 0 :(得分:0)
使用.html()获取文字,如
$('button').on('click', function() {
var colour = $.trim( $(this).html() );
alert("You have chosen " + colour);
});
演示:: jsFiddle
答案 1 :(得分:0)
$('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'));
});
查看演示:HERE
答案 2 :(得分:0)
您可以使用html()
按钮获取值,然后查看jsfidle example