【问题标题】:Use a JavaScript variable inside src of script tag在脚本标签的 src 中使用 JavaScript 变量
【发布时间】:2014-07-16 06:41:52
【问题描述】:

Google 提供了它的脚本嵌入代码,通过将该代码放置在我们的网站中来显示趋势图。

<script type="text/javascript" src="//www.google.com.pk/trends/embed.js?hl=en-US&q=iphone&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&h=330"></script>

以上代码显示趋势图。

请注意上述网址中的q=iphone。在这种情况下,我想传递一个 JavaScript 变量值,而不是像 iPhone 这样硬编码一个固定值。

如何在 script 标签的 src 中使用 JavaScript 变量?

我尝试以编程方式创建脚本,它注入了脚本代码,但脚本没有被执行。

我的尝试

document.body.appendChild(document.createElement('script')).src= varHavingScriptURL;

我的尝试is in a JS Fiddle here

【问题讨论】:

  • 向我们展示您以编程方式创建脚本的代码
  • Jsfiddle or demo would be helpful ... 是的,你是对的,所以给我们看看 :-)
  • 使用 jQuery 的getScript 方法可以让你很容易地做到这一点。你试过了吗?
  • @Adil 我已经在我尝试过的问题中添加了代码和 JSfiddle。
  • 检查@epascarello的答案,将该代码放在页面头部标签的脚本标签中

标签: javascript jquery variables attributes embed


【解决方案1】:

经过几个小时的努力,我终于找到了使用 PostScribe 的解决方案。

 // jQuery used as an example of delaying until load.


$(function
 () {
// Build url params and make the ad call
  var str= "magic";
postscribe('#ad', '<script src=//www.google.com.pk/trends/embed.js?hl=en-US&q='+str+'&cmpt=q&content=1&cid=TIMESERIES_GRAPH_0&export=5&w=500&h=330><\/script>');


});

Postscribe

Working Demo

【讨论】:

    【解决方案2】:

    问题是,您不能在页面加载后执行此操作。看脚本源码

    document.write('<iframe width="500" ... </iframe>');
    

    因此,由于document.write,您需要在页面呈现时执行此操作。

    现在看看你做了什么

    document.body.appendChild(document.createElement('script')).src = varHavingScriptURL;
    

    这行不通,你需要打破它

    var scr = document.createElement('script');
    scr.src = varHavingScriptURL;
    document.getElementsByTagName("head")[0].appendChild(scr);
    

    但同样,由于 document.write,它不会工作。

    【讨论】:

    • 如何在页面呈现时执行此操作?小提琴会很有帮助。
    猜你喜欢
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 1970-01-01
    相关资源
    最近更新 更多