我尝试在运行时向页面添加小部件。基于this post,我编写了以下代码。不幸的是,它没有显示任何东西。谁能告诉我为什么?
<script type="text/javascript">
$(document).ready(function () {
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7";
// Use any selector
$(".testWidget").append(s);
});
</script>
<div class="testWidget">
</div>
如果我使用下面相同的脚本,它可以工作并在页面上显示一些信息。但是,我应该动态插入脚本,而不是静态。
<div class="testWidget">
<script src="https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7" type="text/javascript" charset="utf-8"></script>
</div>
答案 0 :(得分:1)
您应该在控制台中收到此警告,Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.
以下是解决此问题的方法:
<script type="text/javascript">
$(document).ready(function () {
// Save a copy of the document.write method
var oldWrite = document.write;
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://widgets.factiva.com/syndication/subscriber/InsertWidget.ashx?tkn=LDyKkRh5SFskMPuGz6nika6Sg%2bqurZ4vspn0e1OvlEQc6JqLTdcyY8%2btC7a9zO0Z42ta%2f%2fl7QbCByRVbs7TTuQ%3d%3d%7c2&typ=0&st=1&target=7";
// After script is loaded, revert document.write to the original
s.onload = function () {
document.write = oldWrite;
};
var $testWidget = $('.testWidget');
// Redefine document.write to make the script's call work
document.write = function (html) {
$testWidget.html(html);
};
$testWidget.append(s);
});
</script>
答案 1 :(得分:0)
您以编程方式包含的脚本标记必须由浏览器进行解析。只需插入脚本标记,JavaScript解释器就不会解析包含的代码。
如果你解释一下你想要最终实现的目标,我很确定这必须是一种更简单的方法。