可能重複:
Facing weird problem while adding and removing class.如何找到一個html元素,然後刪除它?
假設我有以下HTML -
<div class="div_portlet ui-widget ui-widget-content ui-corner-all defaultcontentbg portlet-width default_border default_border_color portlet_space">
<div class="div_header headertitle align_center defaultheadercolor portlet-header-left-padding default_bottom_border default_border_color">
<span class="ui-icon ui-icon-minusthick"></span>
Order Header Level Information</div>
<div id="ordrHdrLvnInfn" class="div_content portlet-width">
我所試圖做的是,檢查是否帶班跨度ui-icon ui-icon-minusthick
是否存在,如果存在,先刪除它然後添加它。我試着在下面的方式,但它不工作
javascript函數::
jQuery.fn.initPortlet = function(parent_component ,header , component){
this.find(header).find('span.ui-icon').remove();
this.addClass("ui-widget ui-widget-content ui-corner-all")
.find(header)
.addClass("headertitle")
.addClass("align_center")
.addClass("defaultheadercolor")
.end()
.prepend('<span class="ui-icon ui-icon-minusthick"></span>')
.find(component);
}
和我打電話這樣這個功能..
$('.div_portlet').initPortlet('.div_portlet','.div_header','.div_content')
應該先去除然後添加它,但如果我多次調用此函數,那麼它只是繼續添加該跨度。
我該怎麼做,或者有沒有更好的方法來做到這一點。 謝謝!
一個建議:改變'.addClass( 「headertitle」)addClass( 「ALIGN_CENTER」)addClass( 「defaultheadercolor」)'到單線'addClass( 「headertitle ALIGN_CENTER defaultheadercolor」)' – diEcho 2011-05-24 11:02:56
。 @ mplungjan - 你能解釋一下嗎?你想要說什麼? – Vivek 2011-05-24 11:08:16
你有小提琴嗎?網頁上有多個div_portlets嗎? – 2011-05-24 11:08:23