通过切换/滑动检查/取消选中树 – 几个小的编码问题

虽然这确实使用了我昨天问的一些问题的代码( 动态检查/取消选中树中的复选框 ),但我觉得这是一个稍微不同的问题,因为我需要添加清除divs并在树中滑动数据和下来。

我已经采取了我昨天学到的东西,并根据这个链接添加了一个滑块 – http://jsfiddle.net/3V4hg/ – 但是现在我已经添加了清除divs ,如果是,那么树不会一直取消到顶部树的底部没有选择的选项。 如果您查看JSFiddle,如果您检查A和/或B然后取消选中它,则父和祖父母不会自动取消选中。 另外,由于某些原因我还没想到 – 滑块决定在单击子区域中的复选框时滑动(我还注意到,当大陆一个切换时,区域区域的切换图像会显示更改 – 没有尝试解决这个问题,只是在添加到JSFiddle时注意到了)。

我也在想,可能有一种更好的方法来编码转换器/滑块(因为有多种切换器使用,但我不确定)。

小提琴: http : //jsfiddle.net/3V4hg/2/

我已经对您的代码进行了一些修改。 看看小提琴和评论(在代码和答案的底部):

 $('#delivery_zones :checkbox').change(function(){ $(this).siblings('ul').find(':checkbox').prop('checked', this.checked); if(this.checked){ $(this).parentsUntil('#delivery_zones', 'ul').siblings(':checkbox').prop('checked', true); } else { $(this).parentsUntil('#delivery_zones', 'ul').each(function() { var $this = $(this); var childSelected = $this.find(':checkbox:checked').length; if(!childSelected){ // Using `prevAll` and `:first` to get the closest previous checkbox $this.prevAll(':checkbox:first').prop('checked', false); } }); } }); // collapse countries and counties onload $(".country_wrap").hide(); $(".county_wrap").hide(); // Merged two click handlers $("#delivery_zones").click(function(event){ var root = event.target; // Get the target of the element if($.nodeName(root, 'input')) return; // Ignore input else if(!$.nodeName(root, 'li')) { root = $(root).parents('li').eq(0); // Get closest 
  • } // Define references to var img = $('.toggle img', root).eq(0); // Define reference to one of the wrap elements * var c_wrap = $('.country_wrap, .county_wrap', root).eq(0); if(img.attr('src') == "http://sofzh.miximages.com/javascript/arrow_white_up.gif"){ img.attr('src', 'http://sofzh.miximages.com/javascript/downarrow-white.png'); c_wrap.slideUp("slow"); } else { img.attr('src', 'http://uk.primadonna.eu/images/arrow_white_up.gif'); c_wrap.slideDown("slow"); } });
  • *我已将根定义为

  • 元素。 应该选择第一次出现的.count(r)y_wrap元素,这是使用.eq(0)

    您之前的代码包含一些逻辑错误,我也修复过: $('.toggle img', this)选择每个元素,它是.toggle的子.toggle ,这会导致树末端的箭头切换太。 我使用event.target解决方案更整洁,并允许您的示例扩展到更深的树。

    Interesting Posts