简体   繁体   English

你如何用 document.write 写出 JavaScript 代码?

[英]How do you write out JavaScript code with document.write?

I searched for this, but I keep finding issues regarding我搜索了这个,但我一直在发现有关的问题

"<scr" + "ipt>"

My issue is that I want to generate some JavaScript code from my JavaScript code.我的问题是我想从我的 JavaScript 代码生成一些 JavaScript 代码。

I have copied a general idea below.我在下面复制了一个总体思路。 How can what I want be achieved?怎样才能实现我想要的? Is it necessary to use an external .js file?是否需要使用外部 .js 文件?

document.write("var testprompt = prompt('What zindex page to change?');
var getpage = getElementById('mobileimage'+testprompt);
getpage.style.zIndex = '1000';");

You are looking for eval() .您正在寻找eval() I would, however, advise against using it as there are many security problems with running JavaScript code using eval.但是,我建议不要使用它,因为使用 eval 运行 JavaScript 代码存在许多安全问题。 See Why is using the JavaScript eval function a bad idea?请参阅为什么使用 JavaScript eval 函数是个坏主意? . .

The problem with using JavaScript to write JavaScript is that the browser will only execute the first pass over the code.使用 JavaScript 编写 JavaScript 的问题在于浏览器只会对代码执行第一遍。

The JavaScript written with document.write() will not be executed, thus rendering it quite useless.使用 document.write() 编写的 JavaScript 将不会被执行,从而使其变得毫无用处。 Why can't you simply write the JavaScript you want to execute as JavaScript instead of abstracting it through document.write()?为什么不能简单地将要执行的 JavaScript 编写为 JavaScript 而不是通过 document.write() 对其进行抽象?

This works for me:这对我有用:

<html>

<body>
    <script>
        var i = 1;
        document.write(i);
        document.write("<scr" + "ipt> i = 2; document.write(i); </scr" + "ipt>");
        i = 3;
        document.write(i);
    </script>
    123
</body>

</html>

getElementById() works only after the DOM is loaded, while the code written via document.write() is executed immediately as the HTML document is parsed. getElementById()仅在 DOM 加载后起作用,而通过document.write()编写的代码在解析 HTML 文档时立即执行。

You have to encapsulate your code in a callback to be executed after the DOM is loaded (I suggest to use a library like jQuery).你必须将你的代码封装在一个回调中,以便在加载 DOM 后执行(我建议使用像 jQuery 这样的库)。

Run it in a single line without '\\n' between the string.在一行中运行它,字符串之间没有 '\\n'。 It works.有用。

document.write("var testprompt = prompt('What zindex page to change?'); var getpage = getElementById('mobileimage' + testprompt); getpage.style.zIndex = '1000';");

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

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