带有切换/滑动的选中/取消选中树-一些小的编码问题

Check/uncheck tree with toggle/slide - few minor coding issues

本文关键字:问题 编码 取消      更新时间:2023-09-26

虽然这确实使用了我昨天问的一个问题中的一些代码(动态选中/取消选中树中的复选框),但我觉得这是一个稍微不同的问题,因为我需要添加清除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 <li>
    }
    // Define references to <img>
    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://uk.primadonna.eu/images/arrow_white_up.gif"){
        img.attr('src', 'http://www.prbuzzer.com/images/downarrow-white.png');
        c_wrap.slideUp("slow");
    } else {
        img.attr('src', 'http://uk.primadonna.eu/images/arrow_white_up.gif');
        c_wrap.slideDown("slow");
    }
});

*我已经将根定义为<li>元素。应该选择第一次出现的.count(r)y_wrap元素,这可以使用.eq(0)来实现。

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