如果我确认我已经安装了 jQuery,
$('<script type="text/javascript"/>').text("alert('boo');").appendTo($("head"));
按预期工作。但是无法在 firebug 或 Chrome 的开发工具中看到该脚本。
没有人建议以这种方式插入脚本,每个人都建议这样做
headtag=document.getElementsByTagName('head')[0];
scripttag=document.createElement('script');
scripttag.type='text/javascript';
scripttag.innerHTML="alert('boo');";
headtag.appendChild(scripttag);
在这种情况下,它在 Firebug 中可见。为什么后者优于前者?为什么 firebug 不显示脚本?
最佳答案
当 jQuery 处理要附加到 DOM 的 HTML 文本时,它总是去掉 <script>
内容第一。它在更新 DOM 后评估脚本。
关于javascript - 为什么用 jQuery 在 head 中插入脚本如此奇怪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16425509/