2011-05-05 118 views
1


我有下面的函數正在用來初始化一個小部件。jquery奇怪的行爲

jQuery.fn.initPortlet = function(parent_component ,header , component){ 
     var o = $(this[0]) 
     this.addClass("ui-widget ui-widget-content ui-corner-all") 
      .find(header)   
      .addClass("headertitle") 
      .addClass("align_center") 
      .addClass("defaultheadercolor") 
      .prepend('<span class="ui-icon ui-icon-minusthick"></span>') 
      .end() 
      .find(component); 
}; 

HTML:

<div class="div_portlet" id="LINEITEM_HEADER" > 
<div class="div_header"><%=hu.getFrameURL(82,83)%> Line Item Header Information</div> 
      <div class="div_content" id="LINEITEM_HEADER_CONTENT"> 

      </div> 
</div> 

它的作用是在widget的左上角添加一個減號圖標。 我有一些ajax調用,因爲這個函數被多次調用並追加一個減號圖標多次。

我打算以這種方式重新編寫此函數,以便調用多少次,只在標題中附加一個減號圖標。
我試過休耕方法,但沒有奏效。

var $minusthick = $('span.ui-icon ui-icon-minusthick'); 
$('div.div_header').find($minusthick).remove().prepend('<span class="ui-icon ui-icon-minusthick"></span>').end(); 

什麼,我特林是刪除所有跨度類名span.ui圖標UI圖標,minusthick最後追加一個減號圖標,但它不是爲我工作。

任何幫助或建議,以便我可以實現我的目標將高度讚賞。
在此先感謝!!!!!

Edit--如下

解決方案工作正常的一個電話,但it fails if i am calling this function again with same parameter它應該是不幸的是我必須調用這個函數幾次......我該怎麼辦this..i試過很多事情,但它的地方,失敗:(:(:(
請再次建議我的一些做法
感謝....

回答

5

您可以使用jQuery.data()跟蹤它是否已被添加:

jQuery.fn.initPortlet = function(parent_component, header, component){ 
     var o = $(this[0]); 
     if (! o.data('widgeted')) { 
      // .data('widgeted') will return NULL before it is set. 
      // So the first iteration of the function will execute 
      // this code block. 
      this.addClass("ui-widget ui-widget-content ui-corner-all") 
       .find(header)   
       .addClass("headertitle align_center defaultheadercolor") 
       .prepend('<span class="ui-icon ui-icon-minusthick"></span>') 
       .end() 
       .find(component); 
     } 
     // We set widgeted to true. Any further calls to this function 
     // (on this DOM node) will not execute the code block above. 
     o.data('widgeted', true); 
}; 
+0

+1爲整潔的把戲:) – 2011-05-05 12:41:15

+0

@斯蒂芬 - 感謝您的回覆,但我想這是什麼意思這個o.data('widgeted')? – Vivek 2011-05-05 12:44:43

+0

+1,我一直這樣做。 – 2011-05-05 12:46:15