【问题标题】:Injecting javascript within innerHTML is not supposed to work so why it does here?在 innerHTML 中注入 javascript 不应该工作,为什么它在这里呢?
【发布时间】:2016-03-30 16:00:40
【问题描述】:

根据这个线程Can scripts be inserted with innerHTML? injecting some javascript in innerHTML 不应该工作。

那么为什么它在这种情况下有效:

<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 !!!')">

【问题讨论】:

  • 你确定吗?看到这个fiddle
  • @MoshFeu 是的,我很确定,因为我对其进行了测试并从测试中截取了屏幕截图。我使用纯 Javascript,而不是 jquery,它可以工作。
  • @MoshFeu 也许你的不起作用,因为你使用相对 URL,出于安全原因,它必须是绝对 URL,至少在 chrome 中。

标签: javascript html ajax dom


【解决方案1】:

加载页面时未执行 Javascript。您只是加载具有onclick 属性的&lt;img&gt; 标记,当您单击它们时,将执行属性中的代码。那只是普通的HTML。

分配给.innerHTML 时不会执行的是&lt;script&gt; 标签。

【讨论】:

    猜你喜欢
    • 2020-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    相关资源
    最近更新 更多