這裏是一個辦法做到這一點:
let el = e => angular.element(e);
angular.element.prototype.closest = function (selector) {
if (typeof selector === 'string' && (/^(#|\.).+$/.test(selector) || (/^(a|abbr|acronym|address|applet|area|article|aside|audio|b|base|basefont|bdi|bdo|big|blockquote|body|br|button|canvas|caption|center|cite|code|col|colgroup|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|figcaption|figure|font|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hr|html|i|iframe|img|input|ins|kbd|keygen|label|legend|li|link|main|map|mark|menu|menuitem|meta|meter|nav|noframes|noscript|object|ol|optgroup|option|output|p|param|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|source|span|strike|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video|wbr)$/.test(selector)))) {
if (selector.startsWith('#')) {
// finding via id
let id = selector.substring(1, selector.length), parent = el(this).parent();
while (parent.length) {
if (parent.prop('id') === id) return parent;
parent = parent.parent()
}
} else if (selector.startsWith('.')) {
// finding via class name
let class_name = selector.substring(1, selector.length), parent = el(this).parent();
while (parent.length) {
if (parent.hasClass(class_name)) return parent;
parent = parent.parent()
}
} else {
// finding via tag name
let parent = el(this).parent();
while (parent.length) {
if (parent.prop('tagName') && parent.prop('tagName').toLowerCase() === selector.toLowerCase()) return parent;
parent = parent.parent()
}
}
}
return undefined
};
然後:
el('#selector').closest('#parent').css('color', '#f00');
el('#selector').closest('.parent').css('color', '#f00');
el('#selector').closest('div').css('color', '#f00');
不難這裏http://stackoverflow.com/questions搜索此...很多類似的問題/ 7332179/how-to-recursively-search-all-parentnodes,http://stackoverflow.com/questions/25597321/what-is-the-javascript-equivalent-to-jquery-closest,http://stackoverflow.com/questions/18663941/finding-closest-element-without-jquery – charlietfl
你在問如何重新創建nearest()或如何擴展angular.element(jQlite)? – charlietfl
@charlietfl雅。 'angular.element('#selector')。closest('。parent')'而不是創建'closest'函數。 –