jQuery无法访问文档的某些部分

时间:2014-02-20 06:50:55

标签: jquery

我创建了一个jQuery文档,但是它不能只抓取一种元素中的任何元素".media_container"

以下代码以这种方式运行:

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

    alert('alive');

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

    $('.media_container').hover(function(){
        $(this).css('display', 'none');
    });
});
  1. 'alive'会收到提醒,因此我知道该文件正在正确读取。
  2. .media_container内标题的所有标题除了变为粉红色。
  3. 当我将鼠标悬停在任何.media_containers
  4. 上时,没有任何反应

    我在同一个php页面上使用不同的jQuery文件时遇到了同样的问题。 我尝试使用相同的不响应.mouseover和.mouseenter。

    问题:使用jQuery,文档的某些部分无法通过$()访问,并且不可访问的部分只在一个元素类型中,。media_container - 任何关于它为什么的想法?< / p>

1 个答案:

答案 0 :(得分:0)

我几天来一直在努力解决这个问题,当然事后原因和解决方案似乎很容易。 :)

原因:jQuery对订单和时间安排非常苛刻

  • jQuery(document).ready()在所有元素都写入DOM时运行。
  • 我们使用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>

即使在loadContent()而不是document.ready()上触发window.onload()也不起作用,因为当它运行ajax并使用php将元素插入HTML时,jQuery脚本具有已经运行了。

因此,我做了两件事来加速代码:

  1. 我在loadContent()
  2. 上运行了document.ready()
  3. 在每次ajax / php pull结束时,我添加media_container visibility:hidden<img src='spaceholder.jpg' onload='attachFunctions()'>,其中attachFunctions()在{{}中运行的脚本文件中定义1}}问题解决了!
  4. 新守则:

    head