javascript - jQuery .each(index, item) 默认不提供 jQuery 对象
问题描述
我目前正在使用 jQuery 进行一些 dom 操作。
我有多个地方循环遍历项目,匹配特定的选择器。并在它们上调用一些 jQuery 方法。
假设我们有这样的事情:
我正在循环使用:
myElement.find('.child-selector').each(function (index, item) {
if (item.attr('some-attribute') == 'target-value') {
// Do something
// For instance item.detach()
} else {
item.hide();
}
});
正如您很可能已经猜到的那样,这将引发错误,因为 .attr 未定义。这是完全正常的。
因此,为了使用 attr 或任何其他 jQuery 方法,我需要执行以下操作:
myElement.find('.child-selector').each(function (index, item) {
item = $(item)
if (item.attr('some-attribute') == 'target-value') {
// Do something
}
});
但是我觉得在源代码周围都有这个样板有点烦人。你知道有什么更好的方法来避免一直添加item = $(item)
为第一个语句吗?
解决方案
您可能会制作自己的实用程序方法。您只想确保其他程序员知道它是自定义方法而不是 api 的内置方法。
jQuery.fn.customEachWithObject = function (callback) {
if (callback instanceof Function) {
this.each(function(index, element){
callback(index, $(element));
});
}
};
$('div').customEachWithObject(function(index, $element){
if (index == 0) $element.css('backgroundColor', 'red');
if (index == 1) $element.css('backgroundColor', 'green');
if (index == 2) $element.css('backgroundColor', 'blue');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div> </div>
<div> </div>
<div> </div>
推荐阅读
- react-native - 尝试使用 react-native 应用程序在 firebase db 上推送数据,但它没有做任何事情
- ruby-on-rails - 个人资料视图不显示用户名/详细信息
- html - 什么是 c-wiz 标签?
- python - 如果未设置变量,Jinja2 模板渲染 {{variable}} 代替空字符串
- pdf - 根据在 RMarkdown 中编织为 pdf 还是 docx 更改标题级别
- sql - 用一个表中的另一行更新一行
- javascript - React JS 排序和堆叠列表值
- math - Two's Complement - 方法分析
- postgresql - 仅将实体迁移应用于某些环境
- javascript - 如果该行中的单元格值为 0,则删除 Google 电子表格中的一行