我想用angularjs处理辅助函数(.closest()
和其他函数),但我不知道该怎么做。
我的目标:
let el = e => angular.element(e);
el('#selector').helperFunction();
el('.selector').closest('.parent');
jquery的小例子:
jQuery.fn.extend({
helperFunction: function() {
// do stuff...
}
});
$('#selector').helperFunction();
如何使用angularjs实现这一目标?
答案 0 :(得分:1)
这是一种方法:
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');