【问题标题】:How to add a property to an element?如何为元素添加属性?
【发布时间】:2015-01-26 04:53:59
【问题描述】:

请记住,在 jQuery 中添加了 .prop() 来替换元素的许多布尔类型属性/属性的 .attr()。 我的问题是如何在以下代码中添加“属性”?

以下代码集在功能上按照我的要求执行,但在我的浏览器调试部分中,我看到警告 "JQMIGRATE: jQuery.fn.attr('selected') may use property instead of attribute " 指 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"
                            })
                        )

上述警告指的是代码的第 7 行,即选中:“选中”。在不生成此警告的情况下获得相同代码的可能好方法是什么?
我累了:

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

但是没用!!

【问题讨论】:

    标签: javascript jquery jquery-migrate


    【解决方案1】:

    你试过这样吗?

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

    【讨论】:

    • 我的代码没有任何错误,将 [selected: "selected"] 写入 ["selected": "selected"] 没有任何区别!我们需要生成的输出是。 'selected' 没有任何价值。它是它自己的财产!
    【解决方案2】:

    虽然我仍会在此上下文中使用属性以提高可读性(因为确实应该使用 prop ),但设置属性将在另一个调用中:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 1970-01-01
      • 2011-12-26
      • 2019-03-07
      • 2018-03-02
      • 2021-02-03
      相关资源
      最近更新 更多