首页 > 解决方案 > 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)为第一个语句吗?

标签: javascriptjquery

解决方案


您可能会制作自己的实用程序方法。您只想确保其他程序员知道它是自定义方法而不是 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>&nbsp;</div>
<div>&nbsp;</div>
<div>&nbsp;</div>


推荐阅读