最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery checkbox with li - Stack Overflow

programmeradmin8浏览0评论

I have a series of checkboxes, and everything works except their default behavior has been altered unintentionally so I can no longer check them which is odd since the reason I was using this bit of jquery was to highlight the li around them when they got checked in the first place.

Any ideas?

//Tag cloud
$(".tag-cloud li").toggle(
  function () {
    //$(this).filter(":checkbox").attr('checked', 'true');
    $(this).addClass("selected");
    return;
    //return $(this).filter(":checkbox").attr("checked", true);
  },
  function () {
    //$(this).filter(":checkbox").attr('checked', 'false');
    $(this).removeClass("selected");
    return;
    //$("#sortable").submit();
  }
);

I have a series of checkboxes, and everything works except their default behavior has been altered unintentionally so I can no longer check them which is odd since the reason I was using this bit of jquery was to highlight the li around them when they got checked in the first place.

Any ideas?

//Tag cloud
$(".tag-cloud li").toggle(
  function () {
    //$(this).filter(":checkbox").attr('checked', 'true');
    $(this).addClass("selected");
    return;
    //return $(this).filter(":checkbox").attr("checked", true);
  },
  function () {
    //$(this).filter(":checkbox").attr('checked', 'false');
    $(this).removeClass("selected");
    return;
    //$("#sortable").submit();
  }
);
Share Improve this question asked Oct 31, 2010 at 10:57 holdenholden 13.6k23 gold badges100 silver badges163 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

You can simplify it overall and hopefully eliminate the odd behavior by using a simple .click() event handler, like this:

$(".tag-cloud li").click(function() {
 var cb = $(this).find(":checkbox")[0];
 $(this).toggleClass("selected", cb.checked);
});

This has the benefit of working regardless of what state it was initially in, where as .toggle() will be off for pre-checked boxes.

If you want the <li> itself clickable, we need to be sure not to get in a loop or reverse the toggle when clicking the actual checkbox itself (if it's exposed), like this:

$(".tag-cloud li").click(function(e) {
 var cb = $(this).find(":checkbox")[0];
 //if the click wasn't from the checkbox already, toggle it
 if(e.target != cb) cb.checked = !cb.checked;
 $(this).toggleClass("selected", cb.checked);
});

Try removing the return; lines.

发布评论

评论列表(0)

  1. 暂无评论