代码之家  ›  专栏  ›  技术社区  ›  JoelFan

在jQuery中移除ttr(x)与attr(x,'')

  •  8
  • JoelFan  · 技术社区  · 15 年前

    一般来说 removeAttr(x) attr(x, '') 在jQuery中?

    如果是,什么时候使用每一个?

    5 回复  |  直到 14 年前
        1
  •  9
  •   JohnFx    15 年前

    假设从jQuery库中删除removeAttr(见下文)。我会答应的。

    removeAttr: function( name, fn ) {
            return this.each(function(){
                jQuery.attr( this, name, "" );
                if ( this.nodeType === 1 ) {
                    this.removeAttribute( name );
                }
            });
    

    Jquery 1.4.3 uncompressed version

    尽管它本质上是主观的。我认为使用removeAttr是一种更加自我记录的方法。然而,我可以看到其他人的想法相反。

        2
  •  6
  •   Orbling    15 年前

    属性(x,') 将属性设置为空字符串

    拆卸TTR(x)

        3
  •  3
  •   jball    15 年前

    .removeAttr(x); 相当于 .removeAttribute("x"); 虽然 .attr(x, '') .x 空字符串。见 jQuery removeAttr ref mozilla removeAttribute ref 更多信息。

        4
  •  3
  •   John Strickler    13 年前

    某些属性是布尔值(无论它们存在或不存在)。接受属性 disabled 例如。如果它存在,那么它是真的,它的值是什么并不重要。所以你必须使用 .removeAttr('disabled') .attr('disabled', false); 所以我想答案是语义学。

    这个答案刚刚得到一些支持,这提醒我几年前就回答了这个问题。

    用这个代替属性-

    .prop('disabled', true) // set as disabled
    .prop('disabled', false) // set as enabled
    .prop('disabled') // return boolean (is this disabled?)
    

    不要 使用removeProp('disabled'),因为这将从DOM对象中删除属性(这不是您打算做的事情)。

        5
  •  2
  •   Rostyslav Dzinko Ankit    13 年前

    .removeAttr('name')  // try to remove the attribute 'name' from the DOM
    .attr('name', '')    // set the attribute 'name' to empty string
    

    第二个区别,可能只发生在我身上,是 .removeAttr()