简体   繁体   English

如何向元素添加属性?

[英]How to add a property to an element?

Keeping in mind the addition of .prop() in jQuery replacing .attr() for many boolean type attributes/ properties of an element. 请记住,在jQuery中添加了.prop(),以将.attr()替换为元素的许多布尔类型属性/属性。 My question is how to add a 'Property' in the following code? 我的问题是如何在以下代码中添加“属性”?

The following set of code is functionally doing what I require it to do, but in my browser debug section I see a warning "JQMIGRATE: jQuery.fn.attr('selected') may use property instead of attribute" referring jquery-migrate-1.2.1.js 以下代码集在功能上正在执行我需要执行的操作,但是在我的浏览器调试部分中,我看到一条警告“ JQMIGRATE:jQuery.fn.attr('selected')可能使用属性而不是属性”,引用了jquery-migrate- 1.2.1.js

                    $("<select />",{
                        "class": "align-select",
                        id: "align_select_123"
                    }).append(
                            $("<option />",{
                                value: "left",
                                selected: "selected",
                                html: "Left"
                            }),
                            $("<option />",{
                                value: "right",
                                html: "Right"
                            }),
                            $("<option />",{
                                value: "centre",
                                html: "Centre"
                            }),
                            $("<option />",{
                                value: "justify",
                                html: "Justified"
                            })
                        )

The above mentioned warning refers to the 7th line of the code ie selected: "selected". 上面提到的警告是指代码的第7行,即已选择:“已选择”。 What is the possible good way to get same code working with out generating this warning? 在不生成此警告的情况下获得相同代码的可能的好方法是什么?
I have tired: 我累了:

$("<option />",{
    value: "left",
    html: "Left",
    selected
})

but it didn't worked!! 但是没有用!

Although I would still use the attribute in this context for readability (since it's true that prop should be used), to set the property would be in an other call : 尽管我仍会在此上下文中使用该属性以提高可读性(因为确实应该使用prop),但是要在另一个调用中设置该属性:

$("<option />",{
    value: "left",
    html: "Left", 
}).prop('selected', true),

Have you tried like this ? 你有这样尝试过吗?

$("<option />", {
    value   : "left",
    selected: "selected",
    html    : "Left"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM