源自项目
// 原函数
// childNodes:Dom节点树,查找底层节点,得record对象
const childNodes = containerDom.childNodes
for (const child of childNodes) {
let record: any = {}
const grandchildNodes: any = child.childNodes
for (const grandchild of grandchildNodes) {
switch (grandchild.nodeName) {
case '#text':
if (child.nodeName === 'P' || child.nodeName === 'SPAN') {
record = {
type: 0,
content: {
text: grandchild.textContent
}
}
} else if (child.nodeName === 'H1') {
record = {
type: 4,
content: {
text: grandchild.textContent
}
}
}
break
case 'IMG':
record = {
type: 1,
content: { src: grandchild.src }
}
break
case 'DIV':
if (grandchild.className.match('log-file')) {
record = {
type: 2,
content: { src: grandchild.dataset.href }
}
} else {
console.warn('查到一个不能匹配的项目')
}
break
default:
break
}
if (record.content) {
sortedRecords.push(record)
}
}
现函数
interface INodeArray {
childNode: any
grandchildNode: any
}
// 处理文字/图片/文件节点
const handleTextNode = (props: INodeArray): IRecord => {
const { childNode, grandchildNode } = props
if (childNode.nodeName === 'P' || childNode.nodeName === 'SPAN') {
return { type: 0, content: { text: grandchildNode.textContent } }
} else if (childNode.nodeName === 'H1') {
return { type: 4, content: { text: grandchildNode.textContent } }
}
}
const handleImageNode = (props: INodeArray): IRecord => {
const { grandchildNode } = props
return { type: 1, content: { src: grandchildNode.textContent } }
}
const handleDivNode = (props: INodeArray): IRecord => {
const { grandchildNode } = props
if (grandchildNode.className.match('log-file')) {
return { type: 2, content: { src: grandchildNode.dataset.href } }
}
}
const recordTypeMap = new Map([['#text', handleTextNode], ['IMG', handleImageNode], ['DIV', handleDivNode]])
if (editorMode === 'free') {
const containerDom = document.createElement('div')
containerDom.innerHTML = quillValue
console.log('已包装DOM', containerDom)
// childNodes:Dom节点树,查找底层节点,得record对象
const childNodes = containerDom.childNodes
for (const childNode of childNodes) {
const grandchildNodes: any = childNode.childNodes
for (const grandchildNode of grandchildNodes) {
let record = recordTypeMap.get(grandchildNode.nodeName)({ childNode, grandchildNode })
if (record && record.content) {
sortedRecords.push(record)
} else {
console.log('捕获一个无法归类的记录:%o', grandchildNode)
}
}
}
}