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



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

我使用的代码是这样的:

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

我没有任何CSS文件。

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

任何答案将不胜感激。

使用 .prop() 函数:

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

或者这个语法:

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

js小提琴示例

这是发现时的旧错误报告,以及为什么他们没有重新启用旧功能的说明。

作为一种解决方法,您可以将"Size"与大写字母 S 一起使用:

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

http://jsfiddle.net/g9Hct/

有趣。我不知道为什么会发生这种情况,只能假设这是您假设的jQuery错误。

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

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

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

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

JSFiddle演示了两者的实际操作

相关内容

最新更新