2013-12-11 38 views
0

我想知道如何做到這一點,基本上當選擇jquery的對象來結合。jquery插件構造ID

如果你看看下面的例子,我想結合#toggle-btn-說對象的#toggle-btn-example。

這裏是什麼,我試圖做一個例子:

$.fn.togglebutton = function() { 

     var myId = this; 
     var toggleBtn = '#toggle-btn-'+ myId; 
     var toggleInfo = '#toggle-info-'+ myId; 

     $(toggleBtn).click(function(tb){ 
      tb.stopPropagation(); 
      $(toggleInfo).fadeIn(200); 
      $(toggleBtn).hide(); 
     }); 

     $(toggleInfo).click(function(tb){ 
      tb.stopPropagation(); 
     }); 

     $(document).click(function(){ 

      $(toggleInfo).hide(); 
      $(toggleBtn).show(); 

     }); 

    }; 

    $('example').togglebutton(); 

我的控制檯拋出了這一點:

未捕獲的錯誤:語法錯誤,無法識別的表達式:#撥動btn- [對象的對象]

+0

請把你的相關的HTML .. –

回答

2

this是對jQuery對象的引用!

嘗試:

var toggleBtn = '#toggle-btn-'+ this.attr("id"); 
+0

'this'實際上是一個jQuery對象。 '$ .fn'是'jQuery.prototype'的別名。 –

+0

哦,你是對的,我的壞。修復它。 –

1

你假設this是id。這是不正確的。

更換

var myId = this; 

var myId = $(this).attr("id"); 
+1

'this'已經是一個jQuery對象。 '$ .fn'是'jQuery.prototype'的別名。只要做'this.attr('id')'。 –