javascript 如何在脚本标签内设置变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11457918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:18:10  来源:igfitidea点击:

how to set a variable inside script tag

javascripthtmljavascript-events

提问by Roshanck

I have a page name index.php. And I have a script variable as follows at the top of the page:

我有一个页面名称 index.php。我在页面顶部有一个脚本变量,如下所示:

<script>
    var search_quarry = "some_test";
</script>

At the bottom of the same page I want to add this variable into the srcattribute of a script tag:

在同一页面的底部,我想将此变量添加到src脚本标记的属性中:

<script src=NEED_TO_ADD_HERE></script>

This doesn't work:

这不起作用:

<script src=search_quarry> </script>

Can anyone please tell me how to do this?

谁能告诉我如何做到这一点?

回答by Marc B

You'd need to do with DOM manipulation:

你需要做 DOM 操作:

var search_query = 'some_test';
s = document.createElement('script');
s.src = search_query;
document.getElementsByTagName('head')[0].appendChild(s);

or, as an alternative, though I'm not sure if this'd work:

或者,作为替代方案,虽然我不确定这是否可行:

<script id="fixme"></script>
<script type="text/javascript">
    var search_query = 'some_test';
    document.getElementById('fixme').src = search_query;
</script>

回答by epascarello

Why would you do this? Seems like a hack to make sever code work without fixing the back end

你为什么要这样做?似乎是一种在不修复后端的情况下使服务器代码工作的黑客

Option 1 is with document.write

选项 1 是使用 document.write

<script>
    document.write("<script src='" + search_quarry + "'></scr" + "ipt>");
</script>

Option 2 is to use createElement and appendChild

选项 2 是使用 createElement 和 appendChild

<script>
    var scr = document.createElement("script");
    scr.src = search_quarry;
    document.getElementsByTagName("head")[0].appendChild(scr);  //or use body with document onready
</script>

回答by Alvin Wong

Here's a simple way to do what you want

这是一个简单的方法来做你想做的事

window.onload=function(){
    var script=document.createElement("script");
    script.type="text/javascript";
    script.src=search_quarry;
    document.appendChild(script)
}

Although you would like to change window.onloadinto something else or just put the code inside at the top level, or if using jQuery:

虽然你想window.onload改成别的东西或者只是把代码放在顶层,或者如果使用 jQuery:

$(document).ready(function(){
    $(document).append("<script type='text/javascript' src='"+search_quarry+"'/>");
});

回答by smilebomb

This is not possible. You cannot use a javascript variable inside the declaration tags for javascript. That is the point of the tags: everything inside them is parsed as javascript; everything outside them is not.

这不可能。您不能在 javascript 的声明标签内使用 javascript 变量。这就是标签的重点:其中的所有内容都被解析为 javascript;他们之外的一切都不是。