问题描述:

Js Fiddle

here is the JS i have :

 $( function() {

$('td').click( function() {

$(this).toggleClass("red-cell");

} );

} );

and the style :

td { background: white; cursor: pointer; padding: 2px }

td.red-cell {

background: #339933;

}

Easiest to explain by looking at the jsfiddle. I want to be able to click the table cell and if its green then the radio button "yes" is selected, if clicked again it should toggle to the no radio button. I have the radio buttons on the dog picture currently. Once its working i would change the radio buttons to be hidden... The fiddle above is the closest i can get with my limited knowledge of js. Any suggestions on how i can achieve this?

网友答案:

Unnecessarily tricky using toggle (and less clear when reviewing code weeks/months down the road). Better to explicitly specify what you want done.

jsFiddle Demo

$('td').click( function() {
   var $this = $(this);
   if ( $this.hasClass('red-cell') ){
      $this.removeClass('red-cell');
      $('#radNo').prop("checked", true);
   }else{
      $this.addClass('red-cell');
      $('#radYes').prop("checked", true);
   }
} );
相关阅读:
Top