gpt4 book ai didi

jQuery:什么更有效?许多 ID 特定选择器,或一个 "Contains Prefix Selector"

转载 作者:行者123 更新时间:2023-12-01 02:25:31 25 4
gpt4 key购买 nike

我在一个项目中有一段 JavaScript 代码片段,它在仪表板上缓存了一组 jQuery 对象( anchor 标记):

$.extend(cache, {
dashboard : {
buttons : [
$('#dash-new-lead'), $('#dash-jobs-calendar'),
$('#dash-view-lead'), $('#dash-sales-reports'),
$('#dash-search-leads'), $('#dash-new-job'),
$('#dash-dispatch-jobs'), $('#dash-dispatch-reports'),
$('#dash-manage-employees'), $('#dash-manage-trucks'),
$('#dash-finalize-jobs'), $('#dash-payment-profiles'),
$('#dash-employee-statements'), $('#dash-company-statements'),
$('#dash-finance-reports'), $('#dash-admin-sources'),
$('#dash-admin-statuses'), $('#dash-admin-companies'),
$('#dash-admin-groups'), $('#dash-admin-users'),
$('#dash-admin-dispositions'), $('#dash-search-jobs'),
$('#dash-jobs-calendar-dispatch'), $('#dash-new-lead-dispatch'),
$('#dash-finance-notices')
]
}
});

稍后将每个链接设置为按钮样式(使用 $.each)。每个链接都有一个唯一的 jQuery UI 图标(因此 id 而不仅仅是类选择器)。根据用户的访问级别,某些链接可能存在于 DOM 中,也可能不存在。

我现在想知道使用 jQuery 的 Contains Prefix Selector 是否会更有效:

$.extend(cache, {
dashboard : {
buttons : $('a[id|="dash-"]')
}
});
  1. 优点:更少引用 jQuery 对象 = 更快
  2. 缺点:jQuery 无法使用 document.getElementByID = 较慢

最佳答案

您可以创建一个包含所有身份的选择器:

$.extend(cache, {
dashboard : {
buttons : $('#dash-new-lead,#dash-jobs-calendar,#dash-view-lead,#dash-sales-reports,#dash-search-leads,#dash-new-job,#dash-dispatch-jobs,#dash-dispatch-reports,#dash-manage-employees,#dash-manage-trucks,#dash-finalize-jobs,#dash-payment-profiles,#dash-employee-statements,#dash-company-statements,#dash-finance-reports,#dash-admin-sources,#dash-admin-statuses,#dash-admin-companies,#dash-admin-groups,#dash-admin-users,#dash-admin-dispositions,#dash-search-jobs,#dash-jobs-calendar-dispatch,#dash-new-lead-dispatch,#dash-finance-notices')
}
});

不过,我会考虑向按钮添加一个类,以便使用简单的选择器轻松定位它们。这将使维护代码变得更容易。

关于jQuery:什么更有效?许多 ID 特定选择器,或一个 "Contains Prefix Selector",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4327461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com