UNPKG

@mdui/jq

Version:

拥有和 jQuery 相似 API 的轻量级 JavaScript 工具库

38 lines (37 loc) 1.46 kB
import { $ } from '../$.js'; import { createElement, appendChild, removeChild } from '../shared/dom.js'; import { isFunction, isString, eachArray } from '../shared/helper.js'; import './after.js'; import './before.js'; import './clone.js'; import './each.js'; import './map.js'; import './remove.js'; eachArray(['prepend', 'append'], (name, nameIndex) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any $.fn[name] = function (...args) { return this.each((index, element) => { const childNodes = element.childNodes; const childLength = childNodes.length; const child = childLength ? childNodes[nameIndex ? childLength - 1 : 0] : createElement('div'); if (!childLength) { appendChild(element, child); } let contents = isFunction(args[0]) ? [args[0].call(element, index, element.innerHTML)] : args; // 如果不是字符串,则仅第一个元素使用原始元素,其他的都克隆自第一个元素 if (index) { contents = contents.map((content) => { return isString(content) ? content : $(content).clone(); }); } $(child)[nameIndex ? 'after' : 'before'](...contents); if (!childLength) { removeChild(child); } }); }; });