如何将jQuery插件功能限制为仅某些元素

如何将jQuery插件功能限制为仅某些元素

本文介绍了如何将jQuery插件功能限制为仅某些元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查了jQuery插件站点,该站点教我如何编写基本的插件:

I check the jQuery plugin site, which teach me how to write a basic plugin:

(function( $ ){
  $.fn.maxHeight = function() {
    var max = 0;
    this.each(function() {
      max = Math.max( max, $(this).height() );
    });
    return max;
  };
})( jQuery );

然后,div可以具有maxHeight方法,如下所示:

Then, the div can have the maxHeight method, like this:

var tallest = $('div').maxHeight(); // Returns the height of the tallest div

但是我只希望textarea具有maxHeight函数,而不要具有div.我该怎么办?

But I would like to only textarea have maxHeight function, but not the div. How can I do so?

推荐答案

在检查/保存高度之前,请检查以确保该元素是文本区域.

Check to make sure the element is a textarea before checking/saving the height.

this.each(function() {
    if(this.tagName.toLowerCase() === "textarea") {
        max = Math.max( max, $(this).height() );
    }
});

jQuery插件不为某些元素提供功能,而是为jQuery对象提供功能以使用一组选定的元素.最好的解决方案是使它们尽可能通用,并仅在需要时调用$("textarea").maxHeight().您无需对插件中的textarea做任何特定的操作,并且如果保留现在的状态,则将来如果$('div').maxHeight()成为必需的用例,则无需对其进行更改.

jQuery plugins don't give functions to certain elements, they give functions to the jQuery object for working with a set of selected elements. The best solution would be to keep them as generic as possible and only call $("textarea").maxHeight() when you need it. You aren't doing anything specific to textareas in the plugin and if you leave it as it is now, you don't need to make a change to it in the future if $('div').maxHeight() becomes a required use-case.

这篇关于如何将jQuery插件功能限制为仅某些元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 18:53