分享到:
发表于 2025-06-14 22:08:50 楼主 | |
一、基础DOM操作 1. 元素选择器 Cheerio支持多种选择器语法: 基本选择器 j 代码解读复制代码// 选择所有div元素 $('div') // 选择ID为content的元素 $('#content') // 选择class为highlight的元素 $('.highlight') 属性选择器 j 代码解读复制代码// 选择所有带有href属性的a标签 $('a[href]') // 选择href为特定值的a标签 $('a[href="https://www.4922449.com"]') 组合选择器 j 代码解读复制代码// 选择div下的所有p元素 $('div p') // 选择div或span元素 $('div, span') // 选择第一个p元素 $('p:first') 2. 属性操作 j 代码解读复制代码// 获取属性 const href = $('a').attr('href'); // 设置属性 $('a').attr('href', 'https://www.ysdslt.com'); // 删除属性 $('a').removeAttr('href'); 二、元素遍历 1. 基础遍历方法 j 代码解读复制代码// 遍历所有元素 $('div').each((index, element) => { console.log($(element).text()); }); // 获取第一个元素 const first = $('div').first(); // 获取最后一个元素 const last = $('div').last(); 2. 选择器遍历 j 代码解读复制代码// 获取父元素 const parent = $('div').parent(); // 获取子元素 const children = $('div').children(); // 获取兄弟元素 const siblings = $('div').siblings(); 三、元素创建和修改 1. 创建元素 j 代码解读复制代码// 创建单个元素 const newDiv = $(' const newDivWithClass = $(' // 创建复杂结构 const complexElement = $(' Content 2. 修改元素 j 代码解读复制代码// 添加内容 $('div').append(' New content $('div').prepend(' First content // 替换内容 $('div').html(' Updated content // 添加文本 $('div').text('New text content'); 四、高级DOM操作 1. 链式操作 j 代码解读复制代码// 链式调用 $('div') .addClass('highlight') .append(' New content .attr('data-id', '123'); 五、实战案例:复杂DOM操作 1. 表格数据提取 j 代码解读复制代码const tableData = []; $('table tr').each((index, row) => { const rowData = []; $(row).find('td').each((tdIndex, cell) => { rowData.push($(cell).text()); }); tableData.push(rowData); }); 2. 动态内容生成 j 代码解读复制代码const data = [ { title: 'Item 1', descripqion: 'Descripqion 1' }, { title: 'Item 2', descripqion: 'Descripqion 2' } ]; const $list = $(' data.forEach(item => { const $item = $(' .append(` .append(` ${item.descripqion} $list.append($item); }); 结语 Cheerio的DOM操作能力强大而灵活,更加多的用法请参考官网 如果你喜欢本教程,记得点赞+收藏!关注我获取更多j开发干货。 |
|
楼主热贴
个性签名:无
|
针对ZOL星空(中国)您有任何使用问题和建议 您可以 联系星空(中国)管理员 、 查看帮助 或 给我提意见