DIV CSS 佈局教程網

jQuery 控制 iframe:跨框架選取元素的實例
編輯:JQuery特效代碼     

想在 iframe 裡取得父視窗某個元素的值,或者在父視窗操作 iframe 內的元素,該怎麼寫?以下整理幾個可直接套用的寫法,做法是把 DOM 方法與 jQuery 方法結合。

兩個基本操作

在父視窗中選取 iframe 內的所有單選鈕:

$(window.frames["iframe1"].document).find("input[@type='radio']").attr("checked","true");

在 iframe 中選取父視窗內的所有單選鈕:

$(window.parent.document).find("input[@type='radio']").attr("checked","true");

兩者只差在 window.frames["名字"] 與 window.parent——本質上都是「換一份 document 當搜尋範圍」。

iframe 的 HTML 結構

<iframe src="test.html" id="iframe1" width="700" height="300"
        frameborder="0" scrolling="auto"></iframe>

完整可運行範例

以下在 IE7 中測試通過:

<script type="text/javascript" src="../js/jquery-1.2.6.js"></script>
<script type="text/javascript">
  $(function(){
    $("#t1").hover(function(){ alert(''); });

    // 往 iframe 的 body 追加內容
    // $("iframe").contents().find("body").append("I'm in an iframe!");

    // 用 frames 集合進入 iframe 改樣式
    // $(window.frames["iframe1"].document).find("input[@type='text']").attr("size","30px");

    // 用 contents() 進入 iframe 改 CSS
    // $("#iframe1").contents().find("#d1").css('color','red");

    // 針對 name 屬性定位
    // $(window.frames["iframe1"].document").find("input[@name='t1']").css({background:"#369"});
  });
</script>

<body>
<div>
  <input type="text" id="t1" />
  <iframe id="iframe1" src="child.htm"></iframe>
  <iframe src="child.htm" width="300" height="100"></iframe>
</div>
</body>

其他常見情境

同頁兩個 iframe,改變另一個的 src

<iframe id="leftiframe" ...></iframe>
<iframe id="mainiframe" ...></iframe>

// 在 leftiframe 中改變 mainiframe 的 src
$("#mainframe", parent.document.body).attr("src", "https://www.example.com");

取得 iframe 內某元素的內容

$("#mainiframe").contents().find("someID").html();   // HTML
$("#mainiframe").contents().find("someID").text();   // 純文字

用 find 選 id 也一樣可行

$(window.frames["iframe1"].document).find("#id");

寫法選擇與版本提醒

上面兩條主要路徑各有適用時機:$(window.frames["name"].document) 直接鑽進 iframe 的 document,適合明確知道 iframe 名稱的情況;$("#iframeId").contents() 則從 jQuery 物件出發,可以串接後續的 find、filter,風格更一致。兩者效果相同,選你讀起來順手的即可。

但務必注意版本:範例中的 input[@type='radio'] 這種帶 @ 的屬性選擇器在 jQuery 1.3 之後已失效,請改寫為 input[type='radio']。而 .attr("checked","true") 在 jQuery 1.6 之後也應改用 .prop("checked", true),否則勾選狀態不會如預期改變。

最後,所有跨 iframe 操作都受同源政策約束。iframe 若指向外部網域,上述程式碼一律會丟出安全性錯誤,這種情況只能透過 postMessage 溝通,並在接收端驗證 event.origin。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved