innerhtml中的javascript无法正常工作 [英] javascript in innerhtml not working
问题描述
例如:
<html>
<div id="media">123</div>
<a href="javascript:void(0)" onClick="return fun()">Click</a>
<script type="text/javascript">
function fun() {
document.getElementById("media").innerHTML = '<script type="text/javascript">alert("working");<\/script>';
}
</script>
</html>
单击警报后不显示.
alert("working")
;只是一个例子.我希望它完成另一项JavaScript的工作
.我有一个要通过ajax处理的工作,应该使用innerHTML
alert("working")
; is just an example. I want it to finish one job other javascript
. I have a job to be processed through ajax should have used innerHTML
推荐答案
HTML spec 指定不应执行使用innerHTML插入的脚本标签.这是出于安全考虑.
The HTML spec specifies that script tags inserted using innerHTML should not be executed. This is a security consideration.
如果确定,仍有多种方法可以执行此操作,例如将其添加到img
处理程序中或创建脚本元素,将其插入DOM并更改其text
属性.我不会详细说明这些,因为这样做通常被认为是粗略的.如果您不打算注入脚本,则应在页面源代码中包含script元素.
There are still ways to do this if you are determined, such as adding it to img
handlers or creating a script element, inserting it into the DOM and changing its text
property. I will not elaborate on these, since doing this is generally considered somewhat sketchy. If you are not trying to inject script, you should include the script element in the page source.
这篇关于innerhtml中的javascript无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!