【问题标题】:How to insert <script> with Prototype?如何使用 Prototype 插入 <script>?
【发布时间】:2011-01-05 17:00:16
【问题描述】:

我正在使用 Prototype 插入函数来附加一些包含 &lt;script&gt;...&lt;/script&gt; 的 html。在这个脚本中,我定义了一个新函数。当我读到here Prototype 运行&lt;script&gt; 标签内的脚本,然后将其删除,但所有功能都应该保持可访问性。但从那一刻起,我无法运行我的新功能。

 $('some_id').insert({ bottom: '<script> ... </script>' });

如何解决?最好的是它不会删除&lt;script&gt; 标签。

编辑:

到目前为止,我是这样做的:

var add_here = document.getElementById('prepayment_group_items');
var src = document.createElement('div');
src.innerHTML = 'a lot of html with script tags';
add_here.appendChild(src);

【问题讨论】:

  • 您可能希望在示例中包含您尝试执行的脚本。此外,您可以尝试在脚本元素中添加: type="text/javascript"。
  • 脚本包含类似:函数 update_38172() {...}。这个数字是由 Rails 生成的。当我添加到这个脚本时,这个函数起作用:update_38172();它运行,但只有一次。插入完成后&lt;script&gt; 部分已从 html 中完全删除。

标签: javascript prototype insert script-tag


【解决方案1】:

这个函数会在页面头部添加一个脚本标签,无论你传递什么内容。

function insertScript(script_text) {
    var script_tag = document.createElement('script');
    script_tag.type = "text/javascript";

    var script = document.createTextNode(script_text);
    script_tag.appendChild(script);

    document.getElementsByTagName('head')[0].appendChild(script_tag);
}

我对 jQuery 比对 Prototype 更熟悉,所以我只是在纯 JS 中做到了这一点。

如果需要,将我创建元素的部分和获取 HEAD 元素的部分转换为 Prototype,但使用对 appendChild 的调用而不是 Prototype 的 insert函数,因为它只会按照你的要求做,而不是评估 JS。

当然,既然我看到了您的要求,您也可以尝试将要插入的代码更改为:

window.update_12345 = function() {...}

我不确定这是否适合,但值得一试。

【讨论】:

  • 谢谢,我已经使用 appendChild 完成了,但我比&lt;script&gt; 多放了一点。我将我的解决方案附加到问题
【解决方案2】:

如果你想在头部包含 JavaScript,你可以这样做:

$$('head').first().insert({
    bottom: new Element('script', {
        type: 'text/javascript'
    }).update('function helloWorldToConsole(){console.log("Hello World!")}')
});

这会创建一个新的 SCRIPT 标记并将其插入 HEAD 的底部。但是如果你像这样添加一个外部 JavaScript 文件会更好:

$$('head').first().insert({
    bottom: new Element('script', {
        type: 'text/javascript',
        src: 'http://www.example.com/path/file.js'
    })
});

您可以稍后在脚本中使用这些函数。

【讨论】:

    【解决方案3】:

    试试这个..

        $('<script></script>',{
         type:'custom',
         id:'script1'
        }).appendTo('head').attr('type','text/javascript');
    
        $('#script1').append(< add js code here >);
    

    });

    【讨论】:

      猜你喜欢
      • 2011-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      • 2021-02-27
      • 1970-01-01
      • 2020-06-06
      相关资源
      最近更新 更多