javascript - 如何找到一个html元素然后删除它?

标签 javascript jquery

<分区>

Possible Duplicate:
Facing weird problem while adding and removing class.

假设我有以下 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">

我想做的是,检查 span with class 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')

它应该先删除跨度然后添加它,但如果我多次调用此函数,那么它只会继续添加该跨度。
我该怎么做,或者有更好的方法来做到这一点。 谢谢!!!!!!

最佳答案

您正在将跨度添加到 div_header 之外。你的 .end() 意味着你不再使用你的标题过滤器,所以跨度被添加到你的 ui_widget 的开头......

http://jsfiddle.net/Qjrcg/是你的代码的 fiddle 。如果你看我在前缀之后注释掉了 .end() 。如果您取消注释并注释掉前面的注释,则跨度(我将测试文本放入其中以使其更容易查看)只会创建一次。

希望这能帮助您解决问题。

关于javascript - 如何找到一个html元素然后删除它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6109343/

相关文章:

javascript - 在固定 block 中按比例调整图像大小

javascript - 如何使用每个 ajax 请求更新实例变量?

javascript - 如何根据 AngularJS 中的下拉菜单项更改页面标题

javascript - Mongoose 尝试使用 Promise 处理预保存错误

javascript - 如何让javascript中的某个脚本不被执行?

javascript - 带有 Twitter Typeahead 字段的 Bootstrap 按钮

javascript - 如何让用户在 jQuery 中向下滚动?

javascript - 动态附加后按钮无法正确显示

javascript - 在此网站上运行的交互式动画角色。这个怎么做?

jquery - 将文本换行到未设置的图像宽度