2013-07-29 44 views
-2

我已經創建了很多HTML按鈕,當用戶按下它時,它應該改變背景顏色或做一些事情讓用戶知道它。但是,我不會在開始時創建該事件。
如何更改按鈕背景顏色,因爲有很多按鈕

現在我有麻煩了,是否應該在每個觸發事件中添加大量指令來更改顏色,或者我是否還有一些更簡便的SIMPLE方法。

我想創建一個公共函數,它接收button id,使用它來控制應該突出顯示哪個按鈕。不過,我不知道如何得到這樣的按鈕ID:

$("#upload").bind("click", function(){ 

//I want to get the string 'upload' 
}) 

更方便的方法嗎?我不想爲很多按鈕添加很多很多的指令 。

+0

你有沒有考慮過使用CSS? – mohkhan

+0

'this'裏面的處理程序方法指向點擊按鈕 –

+0

@mohkhan其實,如果我能得到按鈕id,我會用它〜〜.css(「background-color」,「blue」); – Stallman

回答

0

this裏面的事件處理程序的方法將引用點擊按鈕,所以你可以使用this.id得到id。

var buttons = $(":button").bind("click", function(){ 
    buttons.not(this).css('background-color', '') 
    $(this).css('background-color', 'blue') 
}) 

這將在點擊按鈕的背景變爲藍色

演示:Fiddle

不過,我可能更喜歡使用的CSS類來做到這一點

button { 
    background-color: lightgrey; 
} 

button.active { 
    background-color: blue; 
} 

var buttons = $(":button").bind("click", function(){ 
    buttons.filter('.active').removeClass('active') 
    $(this).addClass('active') 
}) 

演示: Fiddle

+0

每次只能突出一個按鈕。 – Stallman

+0

@Stallman查看更新 –

+0

P John我正在嘗試,謝謝。 – Stallman

-1

這是你想要的嗎?

DEMO

HTML

<div data-role=page id=home> 
       <div data-role=header> 
       <h1>Location</h1> 
       </div> 

       <div data-role=content> 

        <a id="ButtonLocation" data-role="button" ><h4>Upload</h4></a> 
       </div> 
</div> 

JS:

$('#ButtonLocation').click(function() { 
    alert($(this).text()) 
}); 
-1

隨着您的具體問題,如果你想要的ID,你可以這樣做:

$("#upload").bind("click", function(){ 
    var upload = $(this).attr('id'); //this is the id 
}) 

k ey是.attr('id')

正如其他海報所提到的,如果你所要做的只是改變背景顏色,你甚至不需要這個。但是,如果你想要一個函數只處理您確定特定的ID,你甚至可以做這樣的事情:

$("button").bind("click", function(){ 
    var thisID = $(this).attr('id'); //this is the id 

    if (thisID == "upload") { 
     $(this).css({"background":"black","color":"white"}); 
    } 
}); 

乾杯,希望幫助。

-1
$(":button").bind("click", function(){ 
      iid=this.id; 
       if(iid=="upload") 
       { 
        $(this).css('background-color', 'blue') 
       } 
       else if(iid=="upload1") 
       { 
        $(this).css('background-color', 'yellow') 
       } 
       else 
       { 

       } 
      }); 
    }); 
相關問題