【问题标题】:Why does some jquery code only work if it's at the end of my html-body section?为什么某些 jquery 代码仅在我的 html-body 部分的末尾才有效?
【发布时间】:2010-11-08 18:02:20
【问题描述】:

我有以下用于创建标签的代码。它在 html 正文部分的末尾起作用,但如果我将它放在开头 - 在定义所有 div 之前,它就不起作用。为什么会这样?

<script type="text/javascript">
    $("ul.tabs li.label").hide();
    $("#tab-set > div").hide();
    $("#tab-set > div").eq(0).show();
  $("ul.tabs a").click(
    function() {
        $("ul.tabs a.selected").removeClass('selected');
        $("#tab-set > div").hide();
        $(""+$(this).attr("href")).show();
        $(this).addClass('selected');
        return false;
    }
  );
  $("#toggle-label").click( function() {
    $(".tabs li.label").toggle();
    return false;
  });
</script>

【问题讨论】:

  • "...before all the divs are defined"应该给你一个线索——如果它们还没有被定义,你的代码怎么可能操纵它们?

标签: javascript jquery document position


【解决方案1】:

这很可能是因为 DOM 还没有准备好,因此它们不存在。

因此您需要执行以下操作:

$(function() {
    // Any code in here will only be executed when the DOM is ready.
});

【讨论】:

  • @coward:这不可靠。它并非始终在每个浏览器中都有效
【解决方案2】:

你需要用一个文档就绪块来包装它。这可以防止代码在页面完全加载之前触发。

<script type="text/javascript">
    $(function() {
      // do something on document ready
      $("ul.tabs li.label").hide();
      $("#tab-set > div").hide();
      $("#tab-set > div").eq(0).show();
      $("ul.tabs a").click(
        function() {
          $("ul.tabs a.selected").removeClass('selected');
          $("#tab-set > div").hide();
          $(""+$(this).attr("href")).show();
          $(this).addClass('selected');
          return false;
        }
      );
      $("#toggle-label").click( function() {
        $(".tabs li.label").toggle();
        return false;
      });
    });
</script>

【讨论】:

  • 这基本上是你学习jQuery的第一件事。
【解决方案3】:
jQuery(function($) {
    // put your code in here and it will be executed
    // when the document has fully loaded.
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-02
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 2015-08-19
    • 2020-10-06
    相关资源
    最近更新 更多