在jQuery中removeAttr(x)与attr(x,”)

jQuery中removeAttr(x)attr(x, '')之间通常有区别吗?

如果是这样,何时使用每一个?

鉴于从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未压缩版本

虽然它本质上是主观的。 我认为使用removeAttr是一种更自我记录的方法。 但是,我可以看到其他人正在思考相反的情况。

它们是完全不同的操作:

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

如果可能, removeAttr(x)将删除对象上的属性,或者删除它并将其重置为默认值(如果它由该对象类的DTD定义)。

.removeAttr(x); 相当于.removeAttribute("x");.attr(x, '')只是将.x设置为空字符串。 有关详细信息,请参阅jQuery removeAttr ref和相应的mozilla removeAttribute ref 。

一些属性是布尔值(无论它们是否存在)。 以属性disabled为例。 如果它存在则为真,则设置的值无关紧要。 因此,您必须使用.removeAttr('disabled')再次启用该元素。 但是,jQuery会对它进行规范化,你可以使用.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对象中删除该属性(这不是您打算做的)。

第一个区别:

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

第二个区别,可能只发生在我身上,是.removeAttr()在Firefox和IExplorer中正常工作但在Chrome中不是很好,在Safari上根本不起作用。