Last active
October 20, 2015 13:09
-
-
Save sofish/0c5f30608ef511281b7d to your computer and use it in GitHub Desktop.
rewrite `parent` and `find` method for jqLite
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.$ = angular.element; | |
// jqLite `.parent([selector])` 支持 selector | |
angular.$.prototype.parent = function(sel) { | |
if(!sel) return angular.$(this[0].parentNode); | |
var list = [].slice.call(document.querySelectorAll(sel)) | |
, currentNode = this[0] | |
, ret; | |
while(currentNode.nodeName !== 'HTML') { | |
currentNode = currentNode.parentNode; | |
var index = list.indexOf(currentNode); | |
if(index !== -1) { | |
ret = currentNode; | |
currentNode = document.documentElement; | |
continue; | |
} | |
} | |
return angular.$(ret); | |
} | |
// jqLite `.find([selector])` 支持 selector | |
angular.$.prototype.find = function(sel) { | |
if(!sel) return angular.$(); | |
var list = [].slice.call(document.querySelectorAll(sel)) | |
, childrens = [].slice.call(this[0].getElementsByTagName('*')) | |
, ret = []; | |
list.forEach(function(el) { | |
if(childrens.indexOf(el) !== -1) ret.push(el); | |
}) | |
return angular.$(ret); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
其实很少有这两个方法的需求,我还没遇到过