开发者

Changing the type of an input element

I have an input type="text" that I want converted to an input type="button". I have tried attr(), but that does not work:

HTML:

<input type="text"></input>

JavaScript:

$('input').attr('type'开发者_如何学C, 'button');

What's wrong?


You can't change the type attribute with jQuery. This is from the jQuery source:

// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
    jQuery.error( "type property can't be changed" );
}

The reason, according to the comment, is that it causes problems in IE. Since jQuery is designed to reduce complications that arise due to differences between browsers, it would go against that idea if it worked in other browsers. I'm assuming that's why the jQuery team have simply removed that ability.

As has already been mentioned, your best option will probably be to replace the input element in question with a new one.


This is partially covered in the documentation:

Note: Internet Explorer does not allow you to change the type attribute of an <input> or <button> element.

That you are prevented from even attempting this in any browser comes from the jQuery source:

// We can't allow the type property to be changed (since it causes problems in IE)
if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
    throw "type property can't be changed";

(Looks like the docs need updating.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜