【问题标题】:Jquery 'html' function Vanilla JS without jQuery [closed]没有jQuery的Jquery'html'函数Vanilla JS [关闭]
【发布时间】:2013-06-10 17:45:29
【问题描述】:

我有一个 jQuery 函数,我想用基本的 javascript (Vanilla) 创建,但遇到了麻烦。

<html>
    <head>
        <title></title>
        <style>#cube1{margin-top:35px;width:305px;height:255px;border:1px solid;}</style>
        <script src='http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js'></script>
        <script>
            function create(){
                var ad  = "<scr"+"ipt type='text/javascript'>";
                ad += "alert('boom');";
                ad += "</scr"+"ipt>";
                $('#cube1').html(ad);
            }
        </script>
    </head>
    <body>
        <div id='cube1' onclick='create()'>Create</div>
    </body>
</html>

我想删除 jquery。

我想创建一个新的 javascript 函数,我可以传递 &lt;div/&gt; #cube1 和字符串变量 ad

该函数会将字符串内容插入&lt;div/&gt; 和/或运行脚本 - 基本上它需要做与jQuery 的html() 函数相同的事情。

这不起作用:

document.getElementById( 'cube1' ).innerHTML = ad;

我需要它来运行脚本(警报)。

非常感谢任何帮助!

【问题讨论】:

  • 为什么要重新发明轮子?你有没有让 jQuery 过于繁重的特定项目需求?
  • @MatthewBlancarte:决定使用原生 API 并不是重新发明轮子。
  • 为什么没有zepto
  • 您为什么要尝试将脚本附加到 &lt;div&gt; 元素?你想在你的实际项目中做什么?需要有比将innerHTML 设置为&lt;script&gt; 更好的解决方案。
  • @CrazyTrain 是的,但这并不能准确地描述 OP 想要做什么。他不像是从零开始。他有工作代码,但想在没有任何明显好处的情况下进行重构......因此,我的评论......

标签: javascript jquery


【解决方案1】:

你可以这样做:

function create(){
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.text = "alert('boom');";
    var cube1 = document.getElementById("cube1");
    if (cube1) { cube1.appendChild(script); }
}

【讨论】:

  • Afaik 并非所有浏览器都支持 &lt;script&gt; 节点上的 innerHTML。我会推荐 .text 属性
  • @Bergi 好电话。我发布时只在 Chrome 中进行了测试。从进一步的测试来看,.innerHTML 的版本似乎在 IE7 中失败,但.text 在我尝试过的所有浏览器(IE7+,以及最新的 Chrome 和 Firefox)中都有效。
猜你喜欢
  • 1970-01-01
  • 2020-07-21
  • 2019-04-23
  • 1970-01-01
  • 2022-10-16
  • 1970-01-01
  • 1970-01-01
  • 2015-06-10
  • 1970-01-01
相关资源
最近更新 更多