2011-07-28 20 views
0

我有以下的HTML代碼:jQuery - 使用類的最後一位找到多個關聯的類?

  <fieldset> 
       <legend><span>Contact Details</span> <span class="edit1">Edit</span><span class="hide1">Hide</span></legend> 
       <div> 
       <!--content--> 
       </div> 
      </fieldset> 


      <fieldset> 
       <legend><span>Contact Details</span> <span class="edit2">Edit</span><span class="hide2">Hide</span></legend> 
       <div> 
       <!--content--> 
       </div> 
      </fieldset> 

與類「hide1」和「hide2」的跨度設置爲顯示:無在頁面加載。

在此代碼,使用jQuery,我試圖做到以下幾點:

  • 如果點擊EDIT1,這個跨度被隱藏起來,並與類「hide1」相關的跨度變得可見。
  • 這應該與代碼中的所有其他跨度相同,例如edit2和hide2。另外,如果我想添加進一步的編輯和隱藏類,該函數也應該能夠處理它,例如edit3和hide3等等。

到目前爲止,我已經能夠找到點擊並隱藏的編輯範圍。我正在努力獲得相關的「隱藏」類。任何人都可以幫我做這個請嗎?這裏是我的jQuery的功能至今:

 var spans = $("#myIntForm").find("span[class^='edit'],span[class^='hide']"); 

     spans.click(function() { 
      var $this = $(this); 
      spans.filter("span[class^='hide']").hide(); 
      if($this.attr('class').substr(0,4)=='edit') 
       { 
        var visible = $this.filter("span[class^='"+$this.attr('class').substr(0,4)+"']"); 
        visible.hide(); 

        //find the class 'hide' with same ending number as class 'edit' and display it. 
        var invisible; 
       } 
     }); 

回答

1

我以前做過類似的事情,這是我更容易界定的類名以某種方式 - 即下劃線,並且還使用一個ID,以幫助選擇像所以:

<span class='edit' id='edit_1'>Edit 1</span> 
<span class='hide' id='hide_1'>Hide 1</span> 

然後你就可以找到相關的類是這樣的:

$(function(){ 
    $('.hide').hide(); 
    $('.edit').click(function(){ 
    //each time an edit class is clicked, show its associated hide div 
    var aNum = $(this).attr('id'); 
    //get the number at the end of the ID of this particular edit div   
    aNum=(aNum.substring(aNum.indexOf('_')+1, aNum.length)); 

    //select and show the associated hide_1 div 
    $('#hide_'+aNum).show(); 

    //hide $(this) 
    $(this).hide(); 
    }); 
}); 

我沒有測試過這一點,但你的想法。 另外一點是,我認爲你不需要將$(this)賦值給var,在代碼中我沒有看到任何可以保證的內容。

希望這有助於

編輯:忘了隱藏單擊編輯DIV,代碼更新

2日編輯:Woops,錯過了密切的支架,還需要有關:)正常工作的子串+1現在 - 有一個例子在這裏: http://jsfiddle.net/rYMtq/

有點無關緊要,現在你得到了一個答案,但一個未關閉支架,就足以讓我夜不能寐:d

+0

這似乎只顯示代碼中最後一個「隱藏」範圍。 – Jonathan

+0

固定它,看編輯^^ – jammypeach

+0

真棒 - 謝謝你:-) – Jonathan

2

我已經先行一步,並改了一下你的jQuery代碼。這是一個jsfiddle與一個工作示例。希望能幫助到你。

var $spans =$("#myIntForm").find("span[class^='edit'],span[class^='hide']"); 

$spans.click(function() { 
    var $this = $(this), 
     $hideSpan = $this.siblings('span[class^="hide"]'), 
     $editSpan = $this.siblings('span[class^="edit"]'); 

    $this.toggle(); 
    $hideSpan.toggle(); 
    $editSpan.toggle(); 

}); 
+0

偉大的東西,作品像一個魅力:-) – Jonathan

相關問題