Jquery chechboxTree和Cookie插件 - 让孩子们有问题

时间:2010-11-16 14:13:41

标签: jquery plugins cookies

我正在使用与jquery的cookie插件相关的checkboxTree插件。 我的问题是,当我点击一个带有“header”类的复选框时,我想设置/取消设置子项的所有cookie(来自标题)。 我怎样才能做到这一点? 这是我的.js代码:

 // When page has loaded, check each checkbox if it's checked (set cookie) or not (unset cookie)
 $(".tree input:checkbox").each(function(){
  var elementId = this.id;

  // Check if a cookie of the element exists
  if($.cookie(elementId)){
   // If so, change attribute to checked
   $(this).attr("checked", "checked");
  }else{
   // If not, change attribute to not checked
   $(this).attr("checked", "");
  }

 });

 $(".tree input:checkbox").change(function(){
  if($(this).attr("class") == "header"){
   if($(this).is(":checked")){
    setCookie(this.id);
    // Set cookie for all children
   }else{
    unsetCookie(this.id);
    // Unset cookie for all children
   }
  }else{
   if($(this).is(":checked")){
    setCookie(this.id);
   }else{
    unsetCookie(this.id);
   }
  }
 });

 function setCookie(element){
  $.cookie(element, "checked");
 }

 function unsetCookie(element){
  $.cookie(element, null);
 }


    $('.tree').checkboxTree({
     onCheck: { 
         node: 'expand' 
        }, 
        onUncheck: { 
            node: 'collapse' 
        }, 
     collapseImage: '../media/images/icons/minus.png',
        expandImage: '../media/images/icons/plus.png'
    });

这是我的HTML代码:

   <div id="filterTree">
     <ul class="tree">
         <li><input type="checkbox" id="Human Ressources" class="header">Human Resources
             <ul>
                 <li><input type="checkbox" id="Finance">Finance
                 <li><input type="checkbox" id="Personnel">Personnel
                 <li><input type="checkbox" id="Post Office">Post Office
                 <li><input type="checkbox" id="House Service">House Service
                 <li><input type="checkbox" id="Reception">Reception
                </ul>
         </ul>
    </div>

1 个答案:

答案 0 :(得分:0)

  if($(this).attr("class") == "header"){
    //selects all input of the type checkbox that are within the ul li elements, each loops trough the list of those elements
    $(this).parents("ul.tree").find("ul li input:checkbox").each(function() {
      if($(this).is(":checked")){  //if this item of the list is checked set a cookie, otherwise unset it.
        setCookie(this.id);
      }
      else {
        unsetCookie(this.id);
      }
    });
  }

并删除

末尾的“,”
expandImage: '../media/images/icons/plus.png',