簡體   English   中英

為什么有些jquery代碼只有在我的html-body部分結尾時才能工作?

[英]Why does some jquery code only work if it's at the end of my html-body section?

我有以下代碼用於創建選項卡。 它工作在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>

這很可能是因為DOM還沒有准備好,因此它們不存在。

因此,您需要執行以下操作:

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

你需要用文件就緒塊包裝它。 這可以防止代碼觸發,直到頁面完全加載。

<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(function($) {
    // put your code in here and it will be executed
    // when the document has fully loaded.
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM