根据这个帖子Can scripts be inserted with innerHTML? 在innerHTML中注入一些javascript 是不可行的。
那么为什么它在那种情况下起作用:
<BR>
Below is the code injected with a div
</BR>
<div id="div_content">
</div>
<script>
function HttpRequest(url){
var pageRequest = false //variable to hold ajax object
/*@cc_on
@if (@_jscript_version >= 5)
try {
pageRequest = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try {
pageRequest = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e2){
pageRequest = false
}
}
@end
@*/
if (!pageRequest && typeof XMLHttpRequest != 'undefined')
pageRequest = new XMLHttpRequest()
if (pageRequest){ //if pageRequest is not false
pageRequest.open('GET', url, false) //get page synchronously
pageRequest.send(null)
embedpage(pageRequest)
}
}
function embedpage(request){
//if viewing page offline or the document was successfully retrieved online (status code=2000)
if (window.location.href.indexOf("http")==-1 || request.status==200)
///document.write(request.responseText)
div_content.innerHTML = request.responseText;
}
HttpRequest("http://localhost/ajax/injecthtml/demo4/external.html") //include "external.html" onto current page
</script>
external.html
<img src="google.jpg" alt="" width="" height="" onclick="alert('Embedded Javascript within innerHTML works !!!')">
<br>
<img src="google.jpg" alt="" width="" height="" onclick="alert('Embedded Javascript within innerHTML works !!!')">
答案 0 :(得分:2)
加载页面时未执行Javascript。您只是加载具有<img>
属性的onclick
标记,当您单击它们时,将执行属性中的代码。那只是普通的HTML。
分配给.innerHTML
时未执行的内容是<script>
个标记。