jQuery从主页面存取控制 iframe 中的元素,参数及方法
从主页面上获取iframe下的某个对象,或使用iframe下的方法,或是获取iframe下某个doc元素,要求兼容各类浏览器,不仅仅ie;
$(function() { $('#abgne_iframe').load(function(){ var $iframe = $(this), $contents = $iframe.contents(); // 取得 iframe 中的元素 $('#btn1').click(function(){ alert($contents.find('#t1').val()); }); // 設定 iframe 中的元素 $('#btn2').click(function(){ $contents.find('#t2').val('我的值是由外部指定的!!'); $contents.find('#t2').css('color', 'red'); }); // 控制 iframe 中的按鈕觸發事件 $('#btn3').click(function(){ $contents.find('#sbtn1').click(); }); // 執行 iframe 中定義的方法 $('#btn4').click(function(){ $iframe.get(0).contentWindow.iframeMethod(); }); // 執行各種動作時可以再判斷 $contents 是否為 null }); });
从上面可以看出:
1、获取iframe下面的某元素时使用jQuery("#frameId").contents().find("#inputId") 可以获取到ID="inputId"的元素;
2、获取iframe下的某方法或某全局对象使用jQuery("#frameId").get(0).contentWindow.iframeMethod(); / jQuery("#frameId").get(0).contentWindow.globalObject;
资料参考页面:http://abgne.tw/jquery/jquery-tips/jquery-access-iframe-element-func.html