我的页面 A 发出了 ajax 调用并引入了片段 B。该片段被添加到 DOM 中,并且该片段中的所有脚本都经过了评估。在该代码片段中,我有 2 个脚本标签:
<script type="text/javascript">
function doOptions(){
alert('doOptions');
}
</script>
<script type="text/javascript">
X = {
x : function(x) {
alert('x');
}
}
</script>
然后,在上述脚本标签中声明的 JS 将在代码片段 B 中使用,如下所示:
<button type="button" onclick="doOptions();"> options </button>
<button type="button" onclick="X.x();"> XX </button>
单击 XX 按钮有效,但单击选项按钮无效。 Firefox 和 IE 都告诉我 doOptions
未定义。为什么?
还有,这是哪一类JavaScript知识?意思是,如果我想的话
最佳答案
This snippet is being added into the DOM and all the scripts in that snipper are eval-ed.
如果您是using innerHTML to insert the script ,它将不起作用 - 脚本内容将不会被解析。有方法get it working with Internet Explorer ,但你永远不会有跨浏览器的解决方案。您应该考虑以不同的格式(例如文本)从 AJAX 请求返回数据,然后使用 DOM 函数创建和附加脚本元素。例如:
// Create the script element
var script = document.createElement("script");
script.type = "text/javascript";
// Set the source as the location of the ajax service
script.src = "http://path.to/myajaxhandler.php?ajaxopt=2&anotheropt=5";
// Add the script element
document.getElementsByTagName("head")[0].appendChild(script);
要么从 AJAX 调用中返回的脚本元素中解析出文本内容,但这会变得更加复杂,因为您需要使用正则表达式(这对于解析 HTML 来说并不理想,但如果返回的内容并不太复杂)。
关于JavaScript 评估,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3366188/