2015-03-08 73 views
-2

我有我創建按鈕的列表:如何將按鈕的值存儲在點擊事件jQuery中

<button> red </button> 
<button> blue </button> 
<button> yellow </button> 

我如何可以存儲已經被點擊了什麼值(假設我點擊紅色),進入我的點擊事件,以便我可以使用我的點擊事件功能中的值?

$('button').on('click', function() { 
    var colour = "red"; 
    alert("You have chosen " + colour); 
}); 

回答

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

0

使用.html()來獲取文本,作爲

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

演示:: jsFiddle