<分区>
Possible Duplicate:
How can I get the content of the file specified as the 'src' of a <script> tag?
这似乎是一个奇怪的问题,但它一直在我的脑海中。假设我有一个引用一个或多个 JavaScript 文件的 HTML 文件,这些文件是本地的,但也可能是外部的。现在出于某种原因(我自己的好奇心),我希望输出这些文件之一的内容,如字符串,并将其写入控制台,甚至 alert
内容。假设我有以下名为 jsFile.js 的 JS 文件:
// JavaScript Document
var testString = "I am just an output... or am I",
testNumber = 1,
testArray = [],
testObject = {};
// random functionality, etc... etc...
if(testNumber > 100){
// do something...
}
我想在打开我的 HTML 页面时这样输出:
但是我不确定该怎么做,我可以在 dom 中找到 SCRIPT
标签并在其上使用一种方法来输出它的内容(见下文)还是我必须读取文件(以某种方式)然后遍历每一行代码,将其收集在一个变量中,然后通过 alert
或 console.log
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Hello World</title>
</head>
<script type="text/javascript" src="jsFile.js"></script>
<script type="text/javascript">
// find the JS node...
window.onload = function(){
var theFile = document.getElementsByTagName("script")[0];
// none of these will work as the code within the jsFile.js is not a DOM object...
console.log(theFile.text); // returns a zero length string
console.log(theFile.innerHTML); // returns a zero length string
console.log(theFile.textContent); // returns a zero length string
}
</script>
<body>
I am just a HTML file... no more, no less...
</body>
</html>
以上是我的第一次尝试,但是这些方法都不起作用,因为脚本的内容不是 DOM 对象。我不需要特定于代码的答案,只需要概念证明、想法或指向正确的方向。如果我说的不对,请说出来,我会改写我的问题。