jQuery - class 的仅原型元素

jQuery - prototype only elements of class

大家好。我想知道是否可以仅对某些 class、类型、名称等元素进行原型制作。

例如:

$.fn.showRequiredError = function(){
    $(this).after('<p class="error">This field is required</p>');
}); 

如果我调用 $("#xxx").showRequiredError(); 这一个就可以工作;


现在我想知道是否可以 "extend" jquery 的功能仅用于 class 的元素。需要

所以例如它看起来像这样:

$(".required").fn.showRequiredError = function(){
    $(this).after('<p class="error">This field is required</p>');
}); 

而且我可以调用 ONLY $(".required").showRequiredError();。
如果我调用 $(".somethingElse").showRequiredError();它什么也做不了。

希望你明白。

P.S.: 这种方法对性能有影响吗?

我完全不明白在这种情况下选择器的用法。只需将函数添加到 jQuery 对象原型:

$.showRequiredError = function(){
    $(".required").after('<p class="error">This field is required</p>');
};

$.showRequiredError()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input class="required">
<input class="not-required">

所有 jQuery 对象都有所有方法,因此您不能限制可以在任何给定 jQuery 对象上调用的方法。

但是,您可以在方法内编写代码来决定是否执行任何操作。因此,您可以检查 jQuery 对象中的元素是否是正确类型的元素,如果不是,则什么都不做。

或者,如果您真的不对 jQuery 对象中的 DOM 元素进行操作,因为您已经知道它们是什么,那么也许您需要一个静态 jQuery 方法改为 $.showRequiredError

$.showRequiredError = function(){
    $(".required").after('<p class="error">This field is required</p>');
});

而且,您可以将其称为 $.showRquiredError()

可以做到这一点,虽然这看起来有点奇怪,通常是由程序员使用插件决定它将哪些元素采取行动。

您可以使用 filter:

$.fn.showRequiredError = function(){
    this.filter(".required").after('<p class="error">This field is required</p>');
    //  ^^^^^^^^^^^^^^^^^^^^--- the new bit

    // See "side note" below
    return this;
}; 

现在,插件做的第一件事是过滤调用它的 jQuery 对象的内容,因此它们只包含 .required 个元素。

它会对性能产生 非常非常小的影响,无需担心。

示例:

$.fn.showRequiredError = function(){
  this.filter(".required").after('<p class="error">This field is required</p>');
  //  ^^^^^^^^^^^^^^^^^^^^--- the new bit

  // See "side note" below
  return this;
}; 

$("div").showRequiredError();
.required {
  color: blue;
}
<div class="foo">This doesn't have 'required'</div>
<div class="foo required">This does have 'required'</div>
<div class="required">So does this</div>
<div>But not this</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


旁注 1:请注意,在对 jQuery 插件的调用中,this 是一个 jQuery 对象,因此编写 $(this) 是冗余的(并且是一个很小的运行时的一些额外工作)。


旁注 2:除非你有其他东西,否则你必须 return,按照惯例 jQuery 插件应该 return this,用于链接。