2012-09-19 31 views
0

我有一个非常粗糙的jQuery插件包装复选框与CSS样式的div和隐藏实际的复选框。我在输入元素上运行插件,但希望插件返回链接的包装div,因为输入元素是不可见的。如何让jQuery插件返回链接的特定元素

(function ($) { 

var methods = {  

    'init': function (options) { 

     var settings = $.extend({ 
      'location' : 'top', 
      'background-color' : 'blue' 
     }, options);    

     return this.each(function() { 
      var $this = $(this); 
      var checked = $this.attr('checked') || ''; 
      $this.wrap('<div class="styled-checkboxes ' + checked + '"></div>'); 
      return $(this).parent('.styled-checkboxes')[0]; 
     }); 
    }   
}; 

$.fn.styledCheckboxes = function (method) { 

    if (methods.method) { 
     // 
    } else if (typeof options === 'object') { 
     return methods.init.apply(this, options); 
    } else { 
     console.log('init without options'); 
     return methods.init.apply(this, null); 
    }   
} 
})(jQuery); 

当我调用该插件像这样:

console.log(
    $('input[type="checkbox"]').styledCheckboxes().after('<p>hello world</p>') 
); 

附加P在复选框,不是在div后添加和控制台跟踪是含有任何输入项目我有一个jQuery选择该页面,而不是包装输入的div。为什么线

return $(this).parent('.styled-checkboxes')[0];

不返回用于链接的股利为对象?

回答

2

原因是因为返回each中的任何内容都不会覆盖返回的对象... each的返回始终是集合本身。

你可以返回this.map的结果,它应该工作像预期的那样map仍将枚举列表中的所有项目,你可以操纵返回的项目:

return this.map(function() { 
     var $this = $(this); 
     var checked = $this.attr('checked') || ''; 
     $this.wrap('<div class="styled-checkboxes ' + checked + '"></div>'); 
     return $(this).parent('.styled-checkboxes')[0]; 
    }); 

活生生的例子:http://jsfiddle.net/wBUzP/(其中“你好世界“是新增加的div

+0

'从每个回报总是集合本身' - 啊对!这就是解释。如果我理解你的方法是正确的,this.map中的'this'就是整个集合,因此集合中的每个项目都会被映射,因此每个项目都会作为映射元素(父项)返回。非常感谢:) – kontur

+0

@kontur - 不客气 – Jamiec

+0

您是否有任何线索知道为什么map函数中的$ this.attr('checked')'会返回undefined,即使对于checked =“checkbox”勾选“',但是当我验证并设置地图返回到'this'时,它再次识别它们。是否有一些关于map函数的方法可以打破$(this)'或'$(this).attr()'的使用方式? – kontur