jQuery attr方法无按钮时失效,需默认展开details标签
问题原因与解决方案
核心问题是异步加载时序不匹配:$(document).ready 仅等待初始DOM加载完成就执行代码,但你通过fetch请求的API数据是异步返回的——此时#HungerGames元素还没被插入到页面中,jQuery选择器找不到目标元素,自然无法设置open属性。而按钮触发时,数据已经渲染完成,元素存在,所以代码能正常生效。
解决方法:在数据插入DOM后执行设置逻辑
将设置open属性的代码放在fetch请求的回调里,确保等API数据渲染到页面后再执行:
示例代码(假设API返回HTML文本):
$(document).ready(function() { // 发起fetch请求 fetch('你的API接口地址') .then(response => response.text()) .then(htmlContent => { // 将获取到的HTML插入页面容器 $('#目标容器ID').html(htmlContent); // 此时元素已存在,设置open属性 $('#HungerGames').attr('open', true); }) .catch(err => console.log('数据加载失败:', err)); });
如果API返回JSON格式数据:
$(document).ready(function() { fetch('你的API接口地址') .then(response => response.json()) .then(data => { // 假设data中包含需要渲染的HTML内容字段 const renderHtml = data.content; $('#目标容器ID').html(renderHtml); // 渲染完成后设置展开 $('#HungerGames').attr('open', true); }); });
若使用jQuery的load方法加载内容:
$(document).ready(function() { $('#目标容器ID').load('你的API接口地址', function() { // load完成后自动执行回调,此时元素已存在 $('#HungerGames').attr('open', true); }); });
内容的提问来源于stack exchange,提问作者Sumit Kashyap
相关产品推荐
相关产品推荐

