更改输入元素的类型

Ran*_*lue 2 html jquery

我有一个input type="text"我想转换成的input type="button".我试过了attr(),但这不起作用:

HTML:

<input type="text"></input>
Run Code Online (Sandbox Code Playgroud)

JavaScript的:

$('input').attr('type', 'button');
Run Code Online (Sandbox Code Playgroud)

怎么了?

Jam*_*ice 6

您无法type使用jQuery 更改属性.这是来自jQuery的源代码:

// 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" );
}
Run Code Online (Sandbox Code Playgroud)

根据评论,原因是它在IE中引起问题.由于jQuery旨在减少由于浏览器之间的差异而引起的复杂性,如果它在其他浏览器中工作,则会违背该想法.我假设这就是为什么jQuery团队只是删除了这种能力.

正如已经提到的,您最好的选择可能是input用新的元素替换有问题的元素.