【问题标题】:Why is inserting a script in head with jQuery so strange?为什么用 jQuery 在 head 中插入脚本如此奇怪?
【发布时间】:2013-05-01 18:55:04
【问题描述】:

如果我确认我已经拥有 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 为什么不显示脚本?

【问题讨论】:

  • 我想知道为什么有人会使用这两种场景中的任何一种而不是仅仅使用alert('boo')
  • 如果你想给页面添加外部脚本,你应该使用jQuery的getScript方法。

标签: javascript jquery dom head


【解决方案1】:

当 jQuery 处理要附加到 DOM 的 HTML 文本时,它总是首先删除 &lt;script&gt; 内容。它在更新 DOM 后评估​​脚本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    相关资源
    最近更新 更多