简体   繁体   English

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

[英]How to set a variable inside script tag

I have a page name index.php.我有一个页面名称 index.php。 And I have a script variable as follows at the top of the page:我在页面顶部有一个脚本变量,如下所示:

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

At the bottom of the same page I want to add this variable into the src attribute 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?谁能告诉我该怎么做?

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>

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>

This is not possible.这不可能。 You cannot use a javascript variable inside the declaration tags for javascript.您不能在 javascript 的声明标签内使用 javascript 变量。 That is the point of the tags: everything inside them is parsed as javascript;这就是标签的意义所在:标签中的所有内容都被解析为 javascript; everything outside them is not.他们之外的一切都不是。

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.onload into 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+"'/>");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM