如何使用JavaScript刷新指定的DOM元素或div
JavaScript实现指定div局部刷新的可行方案
针对你给出的头像div结构,下面分不同使用场景提供可直接复用的实现方案:
场景1:仅刷新头像资源(最常用场景)
如果你的需求是刷新已有的avatar.gif资源(比如用户刚上传新头像,后端资源地址不变但内容已更新),可以直接给img地址加时间戳破除浏览器缓存,不需要改动外层DOM结构,性能最优:
// 获取img元素 const avatarImg = document.getElementById('holla'); // 拼接时间戳参数强制拉取最新资源,不使用本地缓存 avatarImg.src = 'avatar.gif?t=' + new Date().getTime();
场景2:需要整体替换#profile_img的HTML结构
如果刷新后需要修改整个div的内部结构(比如新增头像边框、用户名展示等),可以直接替换DOM内容:
// 找到待刷新的div节点 const profileDiv = document.getElementById('profile_img'); // 直接覆盖内部HTML内容 profileDiv.innerHTML = ` <figure> <img id="holla" src="new-avatar.gif" class="new-border"/> <figcaption>我的新头像</figcaption> </figure> `;
如果需要连外层#profile_img节点一起替换,可以用replaceChild方法:
const oldProfile = document.getElementById('profile_img'); const newProfileHtml = ` <div id="profile_img" class="updated"> <figure> <img id="holla" src="new-avatar.gif"/> </figure> </div> `; oldProfile.parentNode.replaceChild( document.createRange().createContextualFragment(newProfileHtml), oldProfile );
场景3:配合后端接口异步刷新的完整示例
如果需要先从服务端拉取最新数据再刷新,可以参考以下封装:
async function refreshUserAvatar() { try { // 调用后端接口获取最新用户信息 const res = await fetch('/api/user/info'); const userInfo = await res.json(); // 更新头像资源 const avatarImg = document.getElementById('holla'); avatarImg.src = userInfo.avatarUrl + '?t=' + new Date().getTime(); } catch (error) { console.error('头像刷新失败:', error); } } // 需要刷新时调用函数即可 // refreshUserAvatar();
注意事项
- 如果新头像的URL本身会随内容更新生成唯一地址(比如包含版本号、哈希值),无需加时间戳参数,直接替换
src属性即可 - 若使用
innerHTML插入用户可编辑的内容,务必提前做XSS转义,避免安全风险 - 纯属性更新优先选直接修改属性的方案,性能比整体替换DOM高3~5倍
内容的提问来源于stack exchange,提问作者Sense of Science
相关产品推荐
相关产品推荐

