需求: 有个别后端返回接口直接返回html字符串,或者需要从html字符串中获取指定属性
解题思路:
1. 将html字符串转化为html dom
2. 通过dom方法获取到指定类名下的指定属性
以下是从html中获取指定类目下所有的src属性
// html 字符串
let htmlStr = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>测试</title>
</head>
<body>
<div id="IntroductionModule">
<div class="detail_info_wrap">
<img src="https://img11.buyimg.com/n1/jfs/t1/b9d5d5d5d5d5d5d5.jpg" alt="">
<img src="//img11.buyimg.com/n1/jfs/t1/b9d6d6d6d6d6d6d6.jpg" alt="">
<img src="https://img11.buyimg.com/n1/jfs/t1/b9d7d7d7d7d7d7d7.jpg" alt="">
</div>
</div>
<div class="detail_info_wrap">
<img src="https://img11.buyimg.com/n1/jfs/t1/b9d8d8d8d8d8d8d8.jpg" alt="">
<img src="https://img11.buyimg.com/n1/jfs/t1/b9d9d9d9d9d9d9d9.jpg" alt="">
<img src="https://img11.buyimg.com/n1/jfs/t1/b9d0d0d0d0d0d0d0.jpg" alt="">
</div>
</body>
</html>
`
function getImgSrc(htmlStr) {
// 创建一个 DOMParser 实例
const parser = new DOMParser();
// 解析 HTML 字符串为一个 Document
const doc = parser.parseFromString(htmlStr, 'text/html');
// 获取id为 IntroductionModule 的元素
const partBoxes = doc.getElementById('IntroductionModule');
const detailInfoWraps = partBoxes.getElementsByClassName('detail_info_wrap');
if (detailInfoWraps.length > 0) {
// 获取当前 detail_info_wrap 下的所有 img 标签
const images = detailInfoWraps[0].getElementsByTagName('img');
// 遍历所有 img 标签并获取 src 属性
const imgSrcs = [];
for (let j = 0; j < images.length; j++) {
imgSrcs.push(images[j].src); // 输出 img 的 src 属性
}
return imgSrcs.map(item => {
// 如果src属性如果以//开头,会自动添加file://前缀,去掉它
if (item.startsWith("file:")) {
return item.slice(5); // slice(5) 会去掉前5个字符,即 "file:"
}
// 如果字符串不以 "file:" 开头,则返回原字符串
return item;
});
}
return [];
}
console.log('getImgSrc(html)', getImgSrc(htmlStr));
结果:

932

被折叠的 条评论
为什么被折叠?



