2012-08-29 155 views
0

我試圖按照jquery文檔的規範,但我不能初始化按鈕的標籤編程和添加/刪除類。jquery切換按鈕添加刪除類

請看看這個jsbin中的幾行。

http://jsbin.com/akinod/2/edit

HTML

<label for="xAxisToggleBtn"></label> 
<input type="checkbox" id="xAxisToggleBtn"/> 

CSS

.on { 
    background-color: green; 
    color: white; 
} 

.off { 
    background-color:brown; 
    color: white; 
} 

的Javascript

$(window).load(function() { 

     $("#xAxisToggleBtn").button(); 


     $('#xAxisToggleBtn').die('click').live('click', function(){ 

       if($(this).is(':checked')){ 
        $(this).button('option', 'label', 'Turn Off'); 

        //why I cannot add/remove classes to change the theme? 
        $(this).addClass('on'); 
        $(this).removeClass('off'); 

       } else { 
        $(this).button('option', 'label', 'Turn On'); 

        //why I cannot initialize add/remove classes to change the theme? 
        $(this).addClass('off'); 
        $(this).removeClass('on'); 

       } 
     }); 

}); 


//why I cannot initialize the label here? 
$("#xAxisToggleBtn").button('option', 'label', 'Turn Off'); 
$("#xAxisToggleBtn").attr('checked', true); 
$("#xAxisToggleBtn").addClass('on'); 
+0

你熟悉的jQuery.toggleClass方法 - http://api.jquery.com/toggleClass/ –

+0

是的,我試過了,沒有工作。他們的功能行爲是相同的。添加/刪除明確做到這一點,所以問題不在於使用toggleClass.Thanks – Gian

+0

你面臨的問題是什麼? – Ashirvad

回答

1

您必須將該類添加到按鈕小部件中,您的樣式將需要覆蓋jQuery-UI自己,並確保在嘗試操縱它們之前加載元素。

$(function() { 
    $("#xAxisToggleBtn").attr('checked', true) 
     .addClass('on').button({'label': 'Turn Off'}) 
     .button('widget') 
     .addClass('off');   

     $('#xAxisToggleBtn').on('click', function(){     
       if($(this).is(':checked')){ 
        $(this).button('option', 'label', 'Turn Off'); 
       } else { 
        $(this).button('option', 'label', 'Turn On'); 
       } 
       $(this).button('widget').toggleClass('on off'); 
     }); 

}); 
.on { 
    background: green!important; 
    color: white!important;  
} 

.off { 
    background:brown !important; 
    color: white !important;  
} 

DEMO

1

我在這裏再次進行了更改:http://jsfiddle.net/5g2Y6/2/

注:這是一個黑客。按鈕插件沒有任何選項的CSS。請查看更多關於按鈕插件的文檔。 PS:不要使用「live」方法,不推薦使用它。使用jquery「on」方法。

+0

謝謝。 add/remove類在這裏似乎不起作用。當切換時,您是否看到按鈕的背景在棕色和綠色之間切換(按CSS)?謝謝 – Gian

+0

更新了答案和鏈接。 – insomiac