
4.2
重构复杂代码
|
91
HTML
代码片段就可以在其他媒介中重复使用,比如不同的源站或者
PDF
文件,而不会破坏终端用户的体验。
下面的函数接收一个
HTML
片段,然后将
a[href
]
和
img[src]
通过类似
jQuery
的
DOM
工具库
$
转换为绝对路径 :
function absolutizeHtml(html, origin) {
const $dom = $(html)
$dom.find('a[href]').each(function () {
const $element = $(this)
const href = $element.attr('href')
$element.attr('href', absolute)
})
$dom.find('img[src]').each(function () {
const $element = $(this)
const src = $element.attr('src')
const absolute = absolutize(src, origin)
$element.attr('src', absolute)
})
return $dom.html()
}
因为这是一个短小的函数,所以这样编写
absolutizeHtml
是完全可以接受
的。然而,如果之后我们决定将
iframe[src]
、
script[src]
和
link[href]
加到我们希望转换路径的属性列表中时,可能会希望避免同时出现五份类 ...