innerhtml中的javascript无法正常工作 [英] javascript in innerhtml not working

查看:111
本文介绍了innerhtml中的javascript无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

<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屋!

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