Facing weird problem while adding and removing class

前端 未结 2 1114
深忆病人
深忆病人 2021-01-24 13:16


i have below function which is being used to initialize a widget.

jQuery.fn.initPortlet = function( parent_component ,header , component ){
        var o         


        
相关标签:
2条回答
  • 2021-01-24 13:33

    ʞɔɐɯɹoↃɔW sǝɯɐſ gave a good solution to this problem, but here is an explanation why your attempt didn't work:

    The first part of the selector 'span.ui-icon ui-icon-minusthick' is looking for a span with class ui-icon, as you intended, but the second part looks for an element of type <ui-icon-minusthick> which obviously doesn't exist. To select an element with multiple class names, add them all to the same selector just like you would in CSS:

    $('span.ui-icon.ui-icon-minusthick')
    

    Of course, the rest of you code would be a no-op since find($minusthick) will do nothing and therefore the rest of the jQuery chain will have no context in which to operate. This would (I think) work as you expected:

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

    The extra end() call returns the jQuery object to the first selector, in this case div.div_header and there is no need for the final end().

    0 讨论(0)
  • 2021-01-24 13:37

    Not sure what variable o is being used for - but the general point of my alteration below is to check to see if the class has been applied already, using the jQuery hasClass() function.

    jQuery.fn.initPortlet = function( parent_component ,header , component ){
        var o = $(this[0])
    
        if (!this.hasClass('ui-widget'))
        {
          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);
        }
    };
    
    0 讨论(0)
提交回复
热议问题