为什么jQuery的$ .get()不将脚本元素插入DOM? [英] Why doesn't jQuery's $.get() insert script elements into the DOM?

查看:68
本文介绍了为什么jQuery的$ .get()不将脚本元素插入DOM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用$.get()从远程服务器检索HTML代码段,并将该代码段插入DOM.该代码段包含几个基本的HTML元素和一个script元素.所有基本元素都会插入,而script元素不会插入.

I am using $.get() to retrieve an HTML snippet from a remote server and insert that snippet into the DOM. The snippet contains several basic HTML elements and a script element. All of the basic elements get inserted, but the script element does not.

示例片段:

<p>This is a paragraph</p>
<script type="text/javascript">
// JavaScript that will work with the HTML in the snippet
</script>

通过查看在Chrome的Web检查器中检索到的资源,我已经验证了脚本元素在检索到的片段中.那么,为什么$.get()不插入script元素,并且有可能做我想做的事情?

I have verified that the script element is in the retrieved snippet by looking at the resources retrieved in Chrome's web inspector. So, why doesn't $.get() insert the script element and is it possible to do what I am wanting to do?

为澄清起见,我正在使用$.get()检索HTML代码段,然后使用$().html(data)将其插入DOM.

To clarify, I was retrieving the HTML snippet with $.get() and inserting it into the DOM with $().html(data).

推荐答案

应该插入script元素,就像静态内容一样-脚本将不会执行.当您使用 html()插入html时,它将映射到每个元素的 innerHTML 属性.从历史上看,浏览器不会执行以这种方式插入的脚本元素(IE

The script element should be inserted, just as static content - the script will not execute. When you use html() to insert html, it maps to each element's innerHTML property. Historically, browsers don't execute script elements inserted this way (with the exception of IE in certain circumstances).

这也反映在 innerHTML的定义中在HTML 5规范草案中:

This is also reflected in the definition of innerHTML in the draft HTML 5 specification:

注意:使用innerHTML插入的脚本元素在插入时不会执行.

Note: script elements inserted using innerHTML do not execute when they are inserted.

如果要执行脚本,则可以查找元素和 eval()的文本,或从文本创建新的脚本元素并将其正确插入DOM.

If you want to execute the script, you could look up the element and eval() its text, or create a new script element from the text and insert it into the DOM properly.

这篇关于为什么jQuery的$ .get()不将脚本元素插入DOM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆