jQuery jQuery创建具有属性差异的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9898442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:26:03  来源:igfitidea点击:

jQuery create element with attribute differences

jquery

提问by Micah Montoya

Discovered something and am looking into a bit of incite as to why one way works and the other doesn't. Looks to be only an IE7 thing but as IE7, sigh, still needs some support in the apps I work in.

发现了一些东西,我正在调查一些关于为什么一种方法有效而另一种方法无效的煽动。看起来只是 IE7 的东西,但作为 IE7,唉,我工作的应用程序仍然需要一些支持。

Way that works in IE7

在 IE7 中的工作方式

var month = jQuery('<input/>');
month.attr('id', 'DOBmonth');
month.attr('title', 'Enter month');
month.attr('type', 'text');
month.attr('size', '1');
month.attr('maxlength', '2');
month.attr('class', 'numbersOnly');
month.attr('value', mm);

This way doesn't work

这种方式行不通

var month = jQuery('<input/>', {
        id: 'DOBmonth',
        title: 'Enter month',
        type: 'text',
        size: 1,
        maxlength: 2,
        class: 'numbersOnly',
        value: mm
        });

Anyone have an idea why only one way works in IE7 but either is fine in IE8+, FF, Chrome and Safari.

任何人都知道为什么只有一种方式在 IE7 中有效,但在 IE8+、FF、Chrome 和 Safari 中任何一种都可以。

回答by Anthony Grist

The answer can be found in the API for the jQuery()function itself.

答案可以在jQuery()函数本身的 API 中找到。

Note: Internet Explorer will not allow you to create an input or button element and change its type; you must specify the type using <input type="checkbox" />for example. A demonstration of this can be seen below:

Unsupported in IE:

$('<input />', {
    type: 'text',
    name: 'test'
}).appendTo("body");

Supported workaround:

$('<input type="text" />').attr({
    name: 'test'
}).appendTo("body");

注意:Internet Explorer 不允许您创建输入或按钮元素并更改其类型;您必须使用<input type="checkbox" />例如指定类型 。可以在下面看到对此的演示:

IE 不支持:

$('<input />', {
    type: 'text',
    name: 'test'
}).appendTo("body");

支持的解决方法:

$('<input type="text" />').attr({
    name: 'test'
}).appendTo("body");

回答by Joseph

according to jQuery:

根据 jQuery

Note: Internet Explorer will not allow you to create an input or button element and change its type; you must specify the type

注意:Internet Explorer 不允许您创建输入或按钮元素并更改其类型;您必须指定类型

this doesn't work:

这不起作用:

$('<input />', {
    type: 'text',
    name: 'test'
}).appendTo("body");

but this does:

但这确实:

$('<input type="text" />').attr({
    name: 'test'
}).appendTo("body");