使用w3-include-html后,元素增删类的JavaScript失效问题求助
解决w3-include-html引入页脚后JS失效的问题
我之前也碰到过一模一样的坑——用w3-include-html异步加载外部HTML时,DOM元素还没完全加载进来,JS就先跑起来了,自然找不到目标元素导致代码失效。你的问题根源就在这里:你的JS代码在页面初始化时就执行了,但footer.html里的.footlogo_container元素还没被插入到DOM中,后续的addClass/removeClass操作根本没作用在实际元素上,看起来就像代码“失效”了。
下面给你两种靠谱的解决办法:
方法一:利用w3-include-html的加载完成事件
w3-include-html自带了onload回调,会在外部HTML加载并插入DOM后触发,我们可以把resize逻辑放到这个回调里,确保元素存在后再执行代码:
- 先修改页脚的引入标签,添加
onload属性:
<div w3-include-html="footer.html" onload="initFooterResize()"></div>
- 把你的JS代码封装成对应的函数:
function initFooterResize() { (function($) { var $window = $(window), $html = $('.footlogo_container'); function resize() { if ($window.width() < 600) { return $html.addClass('col-xs-15'); } $html.removeClass('col-xs-15'); } $window .resize(resize) .trigger('resize'); })(jQuery); }
这样就能保证JS代码只在页脚元素完全加载到DOM后才执行,自然能正确选中.footlogo_container并应用样式类。
方法二:把JS代码放到footer.html末尾
另一种简单直接的方式是,把resize逻辑直接放在footer.html的最后,这样当footer的DOM元素加载完成后,代码会立即执行:
修改后的footer.html内容:
<footer class="footer" style="margin-bottom: -2%;padding-top: 7%" > <div class="footer-top "> <div class="container" id="cont"> <div class="row"> <div class="footer-col col-md-3 col-sm-3 "></div> <div class="footer-col col-md-3 col-sm-3 "></div> <div class="footer-col col-md-3 col-sm-3 "></div> <div class=" footer-col col-md-3 col-sm-3 footlogo_container" style="cursor: pointer;background: url('logo_imageroots.png');background-size: cover;background-position: center;" onclick="location.href='index.html';"> </div> </div> </div> </div> </footer> <script> (function($) { var $window = $(window), $html = $('.footlogo_container'); function resize() { if ($window.width() < 600) { return $html.addClass('col-xs-15'); } $html.removeClass('col-xs-15'); } $window .resize(resize) .trigger('resize'); })(jQuery); </script>
这种方式不需要修改主页面的代码,直接把逻辑和页脚绑定在一起,适合逻辑比较独立的场景。
内容的提问来源于stack exchange,提问作者Mi8Guy
相关产品推荐
相关产品推荐

