2010-03-30 22 views
0

我有一個自定義jquery函數,我需要綁定到兩個iframe文檔對象。如何將兩個文檔對象綁定到單個jquery函數

目前它只有一個做類似工作:

$(window.frames["iframeName"].document).bind('textselect', function(e) { 

}); 

什麼,我希望做的是一樣的東西:

$(window.frames["iframeName"].document,window.frames["iframeName2"].document).bind('textselect', function(e) { 

}); 
+1

爲什麼不宣佈上述變量的功能和使用兩個獨立的結合呢? – vittore 2010-03-30 02:43:38

回答

1

您可以將匿名函數轉換爲一個名爲並將其用於兩種綁定,如下所示:

$(window.frames["iframeName"].document).bind('textselect', selectStuff); 
$(window.frames["iframeName2"].document).bind('textselect', selectStuff); 

function selectStuff(e) { 
    //Stuff 
} 
+0

工作完美,謝謝! – dbr 2010-03-30 03:07:57

0

而不是使用匿名函數 - 創建一個名爲功能

function myhandler(e) 
{ 
    //body of function 
} 

然後使用命名函數:

$(window.frames["iframeName"].document).bind('textselect', myhandler); 
$(window.frames["iframeName2"].document).bind('textselect', myhandler); 
0

另一種選擇

<body> 
    <iframe name="iframe1" src="text.html" width="100px" height="100px" style="border:1px solid #000"></iframe> 
    <iframe name="iframe2" src="text.html" width="100px" height="100px" style="border:1px solid #000"></iframe> 

    <script type="text/javascript"> 

    $(document).ready(function() { 

     function bindFrameDocuments(eventType, handler) { 
      for (var i = 0; i < window.frames.length; i++) { 
       $(window.frames[i].document).bind(eventType, handler); 
      } 
     } 

     bindFrameDocuments( 
      'textselect', 
      function(e) { 
       // this function runs in the scope of the frame 
       window.parent.console.log(e); 
      } 
     ); 

    }); 

    </script> 
</body> 
相關問題