2014-02-20 22 views
0

我創建一個jQuery文檔的某些部分,但它不能搶僅一種類型的元件的內部的任何元件,".media_container"jQuery的不能訪問的文件

以下代碼以這種方式運行:

jQuery(document).ready(function($) { 

    alert('alive'); 

    $('h1').css('background', 'pink'); 

    $('.media_container').hover(function(){ 
     $(this).css('display', 'none'); 
    }); 
}); 
  1. 'alive'被警告,所以我知道該文件正在被正確讀取。
  2. 所有標題標題內​​變成粉紅色。當我將鼠標懸停在任何.media_containers

我有同樣的問題,同樣的PHP頁面上的其他文件的jQuery

  • 沒有任何反應。 我嘗試使用.mouseover和.mouseenter使用相同的非響應。

    問題:有了jQuery文檔的某些部分不能用$()訪問,而不可訪問的部分只在一個元素類型內,.media_container - 關於這是爲什麼?

  • +3

    你能提供的HTML? – Satpal

    +2

    '.media_containers'或'.media_container' ??顯示你的html – mithunsatheesh

    +0

    如果.media_container在iframe中,jquery不能訪問它。 –

    回答

    0

    我一直在爲此奮鬥了幾天,當然原因和解決方案似乎事後很容易。 :)

    原因:當所有的元素都寫到DOM jQuery是真的finnicky關於順序和時間

    • jQuery的(文件)。就緒()運行。
    • 我們使用AJAX來打印」 .media_container是到頁面

    目前腳本運行時,頁面看起來是這樣的:

    <html> 
    <head> 
    <script> 
        window.onload(){ 
         loadContent(); //which uses ajax to inject php into the html 
        } 
    </script> 
    </head> 
    <body> 
    
         //empty 
    
         <script> 
          jQuery(document).ready(function(){ 
           $('.media_container').someFunction(); 
          }); 
         </script> 
    </body> 
    </html> 
    

    $(document).ready() happens before window.onload()

    因此,即使盡管jQuery腳本位於body的末尾,但它在之前運行,loadContent()腳本head這是由window.onload()觸發。事件

    進一步澄清:序列

    1. Browser reads html/php document, top down. 
    2. Browser reads the script in the `head` and waits for `window.onload()` 
    3. Simultaneously, it loads the `html` elements into the DOM. 
    4. It reaches the end of the document and reads and loads a jQuery script and waits for `jQuery(document).ready()' 
    5. Since it's already basically done with loading the DOM, the jQuery script runs <i>before</i> the window.onload() script runs. 
    

    解決方案:<img onload>

    即使觸發document.ready(),而不是window.onload()loadContent()不起作用,因爲當它運行Ajax和用途php將元素插入HTML中,jQuery腳本已經運行。

    因此,我做了兩兩件事,以加快代碼:

    1. 我對document.ready()
    2. loadContent()在每個AJAX/PHP拉結束,我添加具有visibility:hidden<img src='spaceholder.jpg' onload='attachFunctions()'>一個media_container,其中attachFunctions()在head中運行的腳本文件中定義,並且問題已解決!

    新代碼:

    <html> 
        <head> 
         <script> 
          $(document).ready(function(){ 
           loadContent(); //which uses ajax to inject php into the html 
          }); 
          attachFunctions(){ 
           $('.media_container').someFunction(); 
          } 
         </script> 
        </head> 
        <body> 
         <div class='media_container'></div> 
         <div class='media_container'></div> 
         <div class='media_container'></div> 
         <div class='media_container' style='visibility:hidden'> 
          <img src='spaceholder.jpg' onload='attachFunctions()'> 
         </div> 
        </body> 
    </html>