使用jQuery load导入HTML后,如何默认选中对应颜色的li按钮?
问题解决:导入HTML后默认选中对应颜色按钮
问题原因
$.load()是异步方法,你当前的代码先执行了选中逻辑,此时被导入的颜色按钮还没加载到DOM中,所以无法找到目标元素并添加selected类。必须等待HTML导入完成后,再执行选中操作。
修正后的完整代码
<html> <body> <div id="colorList"> <!--//导入后显示的内容会在这里--> </div> </body> </html> <style> .color-button-box {} .color-button-box li a {} .color-button-box li.selected a {border: red 1px solid;} .color-button-box .ivory {color: #fff;} .color-button-box .beige {color: #eee;} .color-button-box .green {color: green;} .color-button-box .blue {color: blue;} </style> <script type="text/javascript"> $(document).ready(function(){ const selectedColor = "green"; /*先导入HTML,完成后执行选中逻辑*/ $("#colorList").load("/t-shirt.html .color-button-box", function() { // HTML加载完成后,找到对应颜色的a元素,给父li加selected类 document.querySelector(".color-button-box a."+selectedColor).parentNode.classList.add("selected"); }); }); </script>
关键改动说明
- 将选中逻辑移到
load()方法的回调函数中,确保DOM元素加载完成后再执行选中操作 - 移除了原代码中多余的闭合
}); - 清空了
#colorList内的初始内容(因为内容会通过load导入,保留初始内容会重复)
内容的提问来源于stack exchange,提问作者Mulllu S
相关产品推荐
相关产品推荐

