开发者

jQuery: optimze code (background in labels)

I have this jQuery code and I'm not sure if it can be optimized (shorten):

//Checkboxes highlight
$('.show-results-from label').addClass('active');
$('input:checkbox').click(function(){       
    if ($('input:checkbox#a').is(':checked')) {
        $('.label-a').addClass('active');
        $
    } else {
        $('.label-a').removeClass('active');
    }
    if ($('input:checkbox#b').is(':checked')) {
        $('.label-b').addClass('active');
        $
    } else {
        $('.label-b').removeClass('active');
    }
    if ($('input:checkbox#c').is(':checked')) {
        $('.label-c').addClass('active');
        $
    } else {
        $('.label-c').removeClass('active');
    }
});

Here's the corresponding HTML:

<div class="show-results-from">
  <ul>
    <li>See results from:</li>
    <li>
      <label class="label-a">
        <input name="a" type="checkbox" id="a" value="tabs1" checked disabled>
        Products &amp; Services <span>(16)</span></label>
    </li>
    <li>
      <label class="label-b">
        <input name="b" type="checkbox" id="b" value="tabs2" checked>
        Publications <span>(9)</span></label>
    </li>
    <li>
      <label class="label-c">
        <input name="c" type="checkbox" id="c" value="tabs3" checked>
        Other <span>(150)</span></label>
    </li>
  </ul>
</div>

What's happening here is that upon page load all the labels have a class added to them, via CSS the class is styled to visually communicate to the user that that checkbox is selected.

When they click on the label or checkbox, the class is removed and visually the user knows that that checkbox has been deselected.

That's it.

Any idea if the jQuery code can be optimized? Or can I leave it like it is?... It loo开发者_开发问答ks too repetitive to me, but I'm no JavaScript guru.

Thanks in advance for any help on this.


Yup, you can shorten your click handler (or change, I prefer it here) down to find the <label> relatively, like this:

$('input:checkbox').change(function(){ 
  $(this).parent().toggleClass('active', this.checked);
});

This uses .parent() to get the <label>, then .toggleClass() to switch the .active class on/off depending on if it's checked.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜