jQuery-类的仅原型元素

jQuery - prototype only elements of class

本文关键字:原型 元素 jQuery-      更新时间:2023-09-26

大家好。我想知道是否有可能只原型化某些类、类型、名称等的元素

例如:

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

如果我调用$("#xxx").showRequiredError();


现在我想知道是否可以将jquery的功能"扩展"到类的元素。必需的

例如,它看起来是这样的:

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

我可以调用ONLY$(".required").showRequiredError()
如果我调用$(".somethingElse").showRequiredError();它不会有任何作用。

希望你能理解。

附言:这种方法会对性能产生影响吗?

可以这样做,尽管这看起来有点奇怪,但通常是使用插件的程序员决定它将对哪些元素执行操作。

你可以使用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:除非您有其他必须返回的东西,否则按照惯例,jQuery插件应该返回this,用于链接。

在这种情况下,我根本不理解选择器的用法。只需为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元素,因为您已经知道它们是什么,那么您可能需要像$.showRequiredError这样的静态jQuery方法。

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

你可以称之为$.showRquiredError()