Jquery if checkbox is checked add a class

前端 未结 7 2161
梦如初夏
梦如初夏 2020-12-06 01:17

I am trying to add a class when a checkbox is checked.

My jquery:

$(\'input\').attr(\"checked\").change(function(){
$(\'div.menuitem\').addClass(\"me         


        
7条回答
  •  死守一世寂寞
    2020-12-06 01:57

    I'm making the assumption you'll want to toggle the class with the checkbox.

    $('input').change(function(){
      var $this = $(this), $div = $('div.menuitem');
      if( $this.is(':checked') )
      {
        $div.addClass('show');
      }
      else
      {
        $div.removeClass('show');
      }
    }).change();
    

    I've updated this to be a suggested solution @Rails beginner's issue given the comments I've read so far.

    Note the addition of change() on the last line. This is to force change to execute immediately on page load (I'm assuming $('input') waits for document.ready or is after the input:checkbox is created).

提交回复
热议问题