2012-07-20 42 views
0

因此,我使用這個漂亮的小部件來創建選項卡,但是我的編輯器抱怨說它無效並且根據規範是真實的。正如你所看到的,我有兩個id命名相同。我的問題是解決這個問題的正確方法是什麼?使用jQuery的HTML唯一ID - 解決此問題的更好方法

下面是HTML

<ul id="tabs"> 
    <li><a href="javascript:void(0)" name="tab1">Stuff</a></li> 
    {% if not is_passing %} 
     <li><a href="javascript:void(0)" name="tab2">More Stuff</a></li> 
    {% endif %} 
</ul> 

<div id="panes"> 
    <div id="tab1">Tab 1</div> 
    <div id="tab2">Tab 2</div> 
</div> 

<script style="text/javascript"> 
    $(document).ready(function() { 
     $("#panes").children("div").hide();   // Initially hide all content 
     $("#tabs li:first").attr("id","current"); // Activate first tab 
     $("#panes div:first").fadeIn();    // Show first tab content 

     $('#tabs a').click(function(e) { 
      e.preventDefault(); 
      if ($(this).closest("li").attr("id") == "current"){ //detection for current tab 
       return false; 
      } 
      else{ 
       $("#panes").children("div").hide();  //Hide all content 
       $("#tabs li").attr("id","");   //Reset id's 
       $(this).parent().attr("id","current"); // Activate this 
       $('#' + $(this).attr('name')).fadeIn(); // Show content for current tab 
      } 
      return false; 
     }); 
    }); 
</script> 
+0

解決此問題的方法是僅使用唯一標識,並且從不在文檔中多次使用相同標識。 – adeneo 2012-07-20 22:19:21

+0

同意 - 但這顯然會打破jQuery。該ID正在用來打開/關閉標籤.. – rh0dium 2012-07-20 22:20:05

+0

我不明白你爲什麼不能使用唯一的ID。 – Grumpy 2012-07-20 23:06:13

回答

3

這裏有兩個問題:

  1. 在標籤和標籤內容
  2. 有標籤的名稱屬性和標籤內容ID使用#current相同

使用一個類而不是一個id

使用addClassremoveClasshasClass

當然,你必須從你的#current CSS改變.current

而且使用rel代替名字的。

<ul id="tabs"> 
    <li><a href="javascript:void(0)" rel="tab1">Stuff</a></li> 
    {% if not is_passing %} 
     <li><a href="javascript:void(0)" rel="tab2">More Stuff</a></li> 
    {% endif %} 
</ul> 

<div id="panes"> 
    <div id="tab1">Tab 1</div> 
    <div id="tab2">Tab 2</div> 
</div> 


<script style="text/javascript"> 
    $(document).ready(function() { 
     $("#panes").children("div").hide();   // Initially hide all content 
     $("#tabs li:first").addClass("current"); // Activate first tab 
     $("#panes div:first").fadeIn();    // Show first tab content 

     $('#tabs a').click(function(e) { 
      e.preventDefault(); 
      if ($(this).closest("li").hasClass("current")){ //detection for current tab 
       return false; 
      } 
      else{ 
       $("#panes").children("div").hide();  //Hide all content 
       $("#tabs li").removeClass("current");   //Reset 
       $(this).parent().addClass("current"); // Activate this 
       $('#' + $(this).attr('rel')).fadeIn(); // Show content for current tab 
      } 
      return false; 
     }); 
    }); 
</script> 
+0

你需要做的比這更好 - 請舉例。 – rh0dium 2012-07-20 22:21:30

+0

完成。一探究竟。 – 2012-07-20 22:26:27

+0

不錯的工作。你能解釋一下這是如何解決id問題的。我完全刪除id =「Tab1」嗎?如果是的話,關係如何發生? – rh0dium 2012-07-20 22:37:50

相關問題