如何用JS自动识别富文本问答加类并生成FAQ schema
Webflow自动生成FAQ Schema完整代码
以下代码已经整合了你需要的自动加类逻辑和原有结构化数据生成能力,直接替换你之前使用的JS代码即可正常运行,无需额外修改,粘贴到Webflow页面的Body结束标签前的自定义代码区域即可:
// 等待DOM加载完成后执行 document.addEventListener('DOMContentLoaded', function() { const contentContainer = document.querySelector('#content'); if (!contentContainer) return; // 找不到#content容器则终止执行,避免报错 // 第一步:筛选所有以问号结尾的H2,添加.auto-question类 const allH2 = contentContainer.querySelectorAll('h2'); const questionH2List = []; allH2.forEach(h2 => { const text = h2.innerText.trim(); // 同时兼容中英文问号 if (text.endsWith('?') || text.endsWith('?')) { h2.classList.add('auto-question'); questionH2List.push(h2); } }); // 第二步:给每个问题对应的回答内容加.auto-answer类 questionH2List.forEach((currentH2, index) => { let nextElement = currentH2.nextElementSibling; // 获取下一个问题H2的节点,没有则为null const nextH2 = index < questionH2List.length - 1 ? questionH2List[index + 1] : null; // 遍历当前H2之后的所有元素,直到遇到下一个问题H2或#content末尾 while (nextElement && nextElement !== nextH2) { nextElement.classList.add('auto-answer'); nextElement = nextElement.nextElementSibling; } }); // 原有FAQ结构化数据生成逻辑 const questions = document.getElementsByClassName("auto-question"); const answers = document.getElementsByClassName("auto-answer"); const schema = { "@context": "https://schema.org", "@type": "FAQPage", "mainEntity": [] }; for (let i = 0; i < questions.length; i++) { const newSchema = { "@type": "Question", "name": questions[i].innerText, "acceptedAnswer": { "@type": "Answer", "text": answers[i].innerText } }; schema.mainEntity.push(newSchema); } const script = document.createElement('script'); script.type = "application/ld+json"; script.text = JSON.stringify(schema); document.querySelector('body').appendChild(script); });
内容的提问来源于stack exchange,提问作者Joachim
相关产品推荐
相关产品推荐

