2012-06-03 126 views
0

爲什麼這個不工作?當我改變alert('test')"$(this).toggleClass('checked');"並單擊標籤,我看到提示窗口: -/將課程添加到標籤

$(document).ready(function(){ 
    $("label").click(function(){ 
     $(this).toggleClass('checked'); 
    }); 
}); 

<input type="radio" name="hours" id="hours1" value="xyz" style="display: none" /> 
<label for="hours1">10:00</label> 
<input type="radio" name="hours" id="hours2" value="xyz" style="display: none" /> 
<label for="hours2">11:00</label> 
+0

爲什麼你認爲它不工作?你的CSS是什麼? – Gavriel

+1

取而代之的是什麼?不工作是一個不好的描述。 – Oliver

回答

1

請參閱本working code。我希望,它滿足您的需要

$(document).ready(function(){ 
    $("label").click(function(){ 
     if(!$(this).hasClass('checked')){ 
      $(this).addClass('checked'); 
     }else{ 
       $(this).toggleClass('checked'); 
     } 
    }); 
}); 

<input type="radio" name="hours" id="hours1" value="xyz" style="display: block" /> 
<label for="hours1">10:00</label> 
<input type="radio" name="hours" id="hours2" value="xyz" style="display: block" /> 
<label for="hours2">11:00</label> 
+0

這是工作! Thnx很多! –

1

假設你想要做的是有當前選定的複選框的標籤已在「檢查」類:

http://jsfiddle.net/4pQt8/3/

注意:您需要以改進$("label")選擇器,因爲現在它將從文檔中的所有標籤中刪除選中的類。

$(document).ready(function(){ 
    $("input[name=\"hours\"]").change(function(){ 
     if ($(this).attr("checked")) { 
      $("label").removeClass("checked"); 
      $("label[for=\"" + $(this).attr("id") + "\"]").addClass("checked"); 
     } 
    }); 
});