【问题标题】:Load external javascript file and create iframe [duplicate]加载外部javascript文件并创建iframe [重复]
【发布时间】:2017-09-13 20:39:26
【问题描述】:
我需要创建一个返回 iframe 标记的 javascript。
客户将脚本粘贴到 iframe 需要的位置,然后脚本应创建 iframe。
必须是这样的:
<script src="http://www.helloworld.com/script/loadcustomerframe.js" data-customer="14532"></script>
然后脚本应该将 iframe 加载到某处的 url,并且我还需要阅读“data-customer”。
我是后端开发人员 c#,而不是前端。我已经尝试了几天了,我无法让它工作。
请帮忙。
谢谢
【问题讨论】:
标签:
javascript
jquery
html
iframe
frontend
【解决方案1】:
这样的事情应该可以工作:
$(document).ready(() => {
$("[data-customer]").each(function() {
let customerId = $(this).data("customer");
$(this).replaceWith(`<p>This is customer #${customerId}.</p>`);
// The following comment is an example of how you could use an iframe
//$(this).replaceWith(`<iframe src="http://example.org/customer/${customerId}>Hello!</iframe>`);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-customer="1"></div>
<div data-customer="2"></div>
<div data-customer="3"></div>
您只需要让脚本出现一次(很可能在您的<head> 中),它将替换任何具有data-customer 属性的<div>。您只需要为您的<iframe> 找出正确的 URL。
【解决方案2】:
基本上你的 JS 代码就可以解决问题,
首先需要创建一个 JS 代码并将其托管到某个服务器中以通过获取它来获取它,因此您的 JS 代码托管在 https://www.mygreatjscode.com/myjscode.js 中的图像
所以你的 JS 代码会完成剩下的工作,
像这样使用纯 JS(不使用 jQuery 等框架),所以你的 myjscode.js 文件将包含以下内容:
//create an autoexec function
(function(){
var body = document.getElementByTagName("body");
body = body ? body : false;
if (body){
var iframe = document.createElement("iframe");
iframe.setAttribute("id", "MY_CUSTOM_ID");
//here set the url that the iframe will be render
iframe.setAttribute("src", "https://stackoverflow.com/");
//finally insert into the body of page
body.appendChild(iframe);
}
})();
最后你需要像这样将脚本标签插入你的页面
<script src="https://www.mygreatjscode.com/myjscode.js" data-customer="14532"></script>