jquery奇怪的行为

时间:2011-05-05 12:35:02

标签: javascript 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>

它的作用是在小部件的左上角附加一个减号图标。 我有一些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-icon ui-icon-minusthick移除所有span,最后添加一个减号图标,但它对我不起作用。

任何帮助或建议,以便我能实现我的目标将受到高度赞赏 在此先感谢!!!!!

修改 -

下面给出的解决方案适用于一个呼叫,但是it fails if i am calling this function again with same parameter它应该是,并且不幸的是我必须多次调用此函数...我怎么能这样做...我尝试了很多东西但是它在某处失败:( :( :( 请给我一些方法。
再次感谢....

1 个答案:

答案 0 :(得分: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);
};
相关问题