jQuery .append() 操作script模板在Firefox中失效的问题
问题:Firefox中无法向text/html类型的script模板追加内容
页面中定义了如下type="text/html"的script模板:
<script id="template" type="text/html"> <div class="row-item">First:<b>{FirstName}</b></div> </script>
尝试用以下代码动态追加内容时,在Google Chrome中运行正常,但Firefox中完全失效:
$('#template').append('<div class="row-item">Last:<b>{LastName}</b></div>');
复现代码
以下是完整的复现示例:
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="holder">测试Firefox中script模板追加内容</div> <script id="template" type="text/html"> <div class="row-item">First:<b>{FirstName}</b></div> </script>
CSS
body { padding: 100px; } #holder { border: 2px solid #bbb; background-color: #eee; padding: 10px; margin: 10px auto; } .row-item { background-color: lightyellow; padding: 10px; margin:10px; background-color: lightblue; }
JavaScript
$(document).ready(function() { $('#holder').append('准备数据...'); $('#template').append('<div class="row-item">Last:<b>{LastName}</b></div>'); $('#holder').html($('#template').html()); });
解决方案
Firefox对非JavaScript类型的script标签,会将内部内容视为纯文本节点处理,jQuery的append()方法在这类节点上的跨浏览器行为不一致,导致无法正确追加内容。可以通过以下两种方式解决:
方法1:直接操作原生DOM节点的innerHTML
$(document).ready(function() { $('#holder').append('准备数据...'); // 获取原生script节点,直接修改innerHTML const templateNode = $('#template')[0]; templateNode.innerHTML += '<div class="row-item">Last:<b>{LastName}</b></div>'; $('#holder').html($('#template').html()); });
方法2:通过text()方法读写内容并拼接
$(document).ready(function() { $('#holder').append('准备数据...'); // 获取原有内容,拼接后重新设置 const existingContent = $('#template').text(); $('#template').text(existingContent + '<div class="row-item">Last:<b>{LastName}</b></div>'); $('#holder').html($('#template').html()); });
两种方法都能在Chrome和Firefox中正常生效,将追加后的模板内容渲染到页面中。
内容的提问来源于stack exchange,提问作者Eqbal Sohrabi
相关产品推荐
相关产品推荐

