两段jquery代码,自定义within方法分别返回包含于指定元素内的所有某种元素类型(返回数组),以及某元素是否包含于指定元素(返回布尔值):
// Extend jQuery.fn with our new method
jQuery.extend( jQuery.fn, {
// Name of our method & one argument (the parent selector)
within: function( pSelector ) {
// Returns a subset of items using jQuery.filter
return this.filter(function(){
// Return truthy/falsey based on presence in parent
return $(this).closest( pSelector ).length;
});
}
});
jQuery.extend( jQuery.fn, {
// Name of our method & one argument (the parent selector)
within: function( pSelector ) {
return !!$(pSelector).find(this).length
}
});