我的问题是我想将 JavaScript 添加到 html 页面中,感谢 Andy E,我找到了 add my JavaScript into a html page and be executed 的方法。但现在我的问题是所有页面都被 JavaScript 覆盖了。有人知道如何做同样的事情,但不使用 JavaScript 覆盖页面,需要在代码中添加一些内容或进行一些更改:)?
- 我不想重新加载页面,因为我不希望用户看到该页面两次,如果页面包含很多内容会很不方便。
这是一个简短的代码,它向您展示了我的问题:(我更改了广告代码,因为它不是我的,所以我不能将其放在这个公共(public)场所)
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {;
var correct_div = document.getElementById('ad_468x60');
var sTag1 = document.createElement("script");
sTag1.type = "text/javascript";
sTag1.text = "<!--\ngoogle_ad_client = \"pub-1234567890123456\";\ngoogle_alternate_color = \"FFFFFF\";\ngoogle_ad_width = 468;\ngoogle_ad_height = 60;\ngoogle_ad_format = \"468x60_as\";\ngoogle_ad_channel =\"123456789\";\ngoogle_color_border = \"FFFFC6\";\ngoogle_color_bg = \"FFFFFF\";\ngoogle_color_link = \"000000\";\ngoogle_color_url = \"666666\";\ngoogle_color_text = \"333333\";\n//-->"
correct_div.appendChild(sTag1);
var sTag2 = document.createElement("script");
sTag2.type = "text/javascript";
sTag2.src = "http://google_ad_url.js";
correct_div.appendChild(sTag2)
});
</script>
</head>
<body>
<div>
"This text appears and disappears after the ad is displayed"
</div>
<div id="ad_468x60">
<!-- The JavaScript come here -->
</div>
</body>
</html>
编辑:我可以使用 iframe 来执行此操作吗?
最佳答案
您可以做几件事。
将脚本添加到空 iframe。这将导致 iframe 内容被 document.write 覆盖。您需要将 iframe 调整为适当的尺寸。
用您自己的方法覆盖document.write函数。像这样的事情:
// Create a closure to keep the old document.write private (function () { var oldDW = document.write; document.write = function (s) { // Document not parsed yet, allow document.write: if (document.readyState != "complete") oldDW.call(document, s); // Dangerous use, switch to innerHTML instead: else document.getElementById("ad_468x60").innerHTML = s; } })();
正如您现在所知,如果有 document.write() 编写的任何脚本元素,则第二种方法不会削减它 - 您必须编写一个更复杂的例程来解析取出脚本元素并使用 document.createElement() 代替。
关于javascript - 动态添加的 JavaScript 覆盖 html 页面 View (而不是代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3427130/