如何使用属性对象为元素<input />设置'size'属性?

时间:2013-10-24 20:39:51

标签: jquery

我是一名jQuery初学者,并且遇到过在页面上创建新元素的方法之一。我能够很好地创建元素。但是,其中一个属性(大小)默认为20,即使我明确指出它应该更大。这是一个jQuery错误,还是我错过了什么?属性对象中的其他属性(类型,自动对焦)工作正常。

我使用的代码是:

$('<input>', {
  'type' : 'text',
  'size' : 50,
  'autofocus' : 'true'
});

我没有任何CSS文件。

当我使用attr()方法时,我可以设置大小。但我想知道我不是唯一一个无法使用属性对象为元素设置size属性的人。我正在使用jQuery 1.9.1。

任何答案都将不胜感激。

3 个答案:

答案 0 :(得分:2)

使用.prop()功能:

$('<input>', {
  'type' : 'text',
  'autofocus' : 'true'
}).prop('size','50');

或者这个语法:

$('<input>', {
   'type': 'text',
    prop: {
        size: "50"
    },
   'autofocus': 'true'
})

<强> jsFiddle example

这是发现它时的old bug report,以及解释为什么它们没有重新启用旧功能。

答案 1 :(得分:1)

作为一种解决方法,您可以将“大小”与资本S:

一起使用
$('<input>', {
  'type' : 'text',
  'Size' : 50,
  'autofocus' : 'true'
});

http://jsfiddle.net/g9Hct/

答案 2 :(得分:0)

有趣。我不知道为什么这种情况正在发生,并且只能假设这是一个jQuery错误。

您已经知道使用attr()来设置大小,但是为了参考,您可以在创建元素之后直接调用它(在将其添加到页面之前或以任何其他方式影响它)之前: / p>

$('<input>', {
  'type' : 'text',
  'autofocus' : 'true'
}).attr('size', 50);

另一种方法是简单地在选择器中添加属性:

$('<input type="text" autofocus="true" size="50">');

JSFiddle demo of both in action