【问题标题】:Retrieve element with attr instead of setting the attr使用 attr 检索元素而不是设置 attr
【发布时间】:2011-12-12 23:11:17
【问题描述】:

使用此代码:$('#ipadmenu section').attr('data-order', hash) 我正在将 data-order 属性设置为“hash”的值。如何选择具有该属性/值的元素而不是设置值?

感谢您的帮助!

附:我正在使用 zepto.js 并且不支持 .prop()

【问题讨论】:

    标签: javascript jquery zepto


    【解决方案1】:

    With the attribute selector.

    $("#ipadmenu section[data-order='" + hash + "']")

    【讨论】:

    • 我该如何改进呢?通过选择特定节点?
    • @SnippetSpace 添加了对答案的改进,只需指定元素 ID 并具体使用标签。这将最大限度地减少对匹配此属性的元素的搜索。 (将此作为选择器的一般经验法则)
    【解决方案2】:

    简单。使用attribute selector$("#ipadmenu section[data-order='" + hash + "']")

    【讨论】:

    • 那是因为我错过了hash 是一个变量,而不是一个常量这一事实。
    猜你喜欢
    • 1970-01-01
    • 2014-09-01
    • 2021-09-05
    • 1970-01-01
    • 2013-03-31
    • 2015-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多