【问题标题】:How do I write executable jQuery for a parent JavaScript file?如何为父 JavaScript 文件编写可执行的 jQuery?
【发布时间】:2012-10-08 23:28:41
【问题描述】:

我有两个JavaScript 文件。第一个文件设置变量并写入另一个名为 iframe.js 的文件的内容:

/* Parent File  */
var aff_id = 2; // Your affiliate ID
var aff_source_id='1'; // Your site ID
var aff_source_subid=''; // Your custom tracking ID
var thankyouUrl = ''; // Leave blank if you don't have a thank you page
var live = 0; // 1 for production
var lead_type = 1; // Auto insurance
document.write(unescape('%3Cscript src="'+site+'/api/js/iframe.js"%3E%3C/script%3E'));
/* Child File */
if(!site) var site='https://leadthis.com';
$(function(){
    var height,width,src = 'http://lead/api/iframe/insurance/auto.php#'+encodeURIComponent(document.location.href )+'?aff_id='+aff_id+'&aff_source_id='+encodeURIComponent(aff_source_id)+'&aff_source_subid='+encodeURIComponent(aff_source_subid)+'&live='+live,
    emarfi=$('<iframe id="appframe" src="'+src+'" scrolling="no" frameborder="0"><\/iframe>').appendTo('#emarfi');
});
document.write('<div id="emarfi"><\/div>');

我想在这个子文件中编写一些可执行的 JavaScript 代码来处理写入父文件的 iframed 内容。这可能吗?我试过这个:

document.write("$(function(){ $('iframe').load(function(){alert('Hello Iframe');})});");

我做错了什么?

【问题讨论】:

  • 一些建议:尽可能远离document.write。不要使用全局变量,创建自己的命名空间(对象)。了解 AJAX,这样您就不需要庞大的 src 行,并且您的代码将变得更加明显且更易于维护。
  • 这是一个类似的thread
  • 感谢 krg,但我需要跨域解决方案。
  • 看看this。没试过,但看起来很有希望。
  • 这更接近我正在寻找的东西。再次感谢。

标签: javascript jquery iframe iframe-app


【解决方案1】:

我已经根据 krg 的评论开始使用 Porthole,而这正是我所需要的。谢谢。 http://ternarylabs.com/2011/03/27/secure-cross-domain-iframe-communication/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 2012-12-06
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    相关资源
    最近更新 更多