如何用JavaScript将指定ID元素的AppointmentDescription文本替换为title中的姓名?
解决方案:替换预约描述文本为对应姓名
1. 定位目标容器
首先用属性选择器获取所有ID以PlanningBoard_RadScheduler开头的div元素:
const containers = document.querySelectorAll('[id^="PlanningBoard_RadScheduler"]');
[id^="xxx"]是CSS属性选择器,专门匹配ID以指定字符串开头的元素,刚好符合你的需求。
2. 提取title中的姓名
假设你的容器title格式是company: Bobby Bob或lunch: Joey Joe,可以用正则表达式精准捕获company/lunch后的姓名:
const nameMatch = container.title.match(/(company|lunch):\s*(.+)/); // 匹配成功的话,nameMatch[2]就是我们要的姓名
(company|lunch):匹配title里的关键词\s*:忽略关键词和姓名之间的空格(不管有没有空格都能匹配)(.+):捕获后续的完整姓名
如果title格式固定用冒号分隔,也可以用更简单的字符串分割:
const name = container.title.split(':')[1].trim();
3. 替换描述文本
找到容器内的AppointmentDescription子元素后,直接用textContent覆盖原文本即可(不需要用replace,因为我们要替换整个内容):
完整可运行代码
// 获取所有目标容器 const containers = document.querySelectorAll('[id^="PlanningBoard_RadScheduler"]'); // 遍历每个容器处理 containers.forEach(container => { // 提取姓名 const nameMatch = container.title.match(/(company|lunch):\s*(.+)/); if (!nameMatch) return; // 格式不符合则跳过当前容器 const targetName = nameMatch[2]; // 找到需要替换的描述元素 const descElement = container.querySelector('.AppointmentDescription'); if (!descElement) return; // 找不到元素则跳过 // 替换文本 descElement.textContent = targetName; });
代码适配的HTML示例
<div id="PlanningBoard_RadScheduler_01" title="company: Bobby Bob"> <div class="AppointmentDescription">company</div> </div> <div id="PlanningBoard_RadScheduler_02" title="lunch: Joey Joe"> <div class="AppointmentDescription">lunch</div> </div>
关键细节说明
- 代码里加了
if (!nameMatch)和if (!descElement)判断,避免因格式错误或元素缺失导致报错 - 如果页面是动态加载的这些元素,要确保代码在元素渲染完成后执行(比如放在
DOMContentLoaded事件里,或者在元素加载完成的回调中调用)
内容的提问来源于stack exchange,提问作者Ahmed Faqiri
相关产品推荐
相关产品推荐

