如何将jQuery插件函数仅限制为某些元素?
我查看了jQuery插件网站,该网站教我如何编写基本插件:
(function( $ ){ $.fn.maxHeight = function() { var max = 0; this.each(function() { max = Math.max( max, $(this).height() ); }); return max; }; })( jQuery );
然后,div可以有maxHeight
方法,如下所示:
var tallest = $('div').maxHeight(); // Returns the height of the tallest div
但我想只有textarea有maxHeightfunction,但不是div。 我怎么能这样做?
在检查/保存高度之前,检查以确保元素是textarea。
this.each(function() { if(this.tagName.toLowerCase() === "textarea") { max = Math.max( max, $(this).height() ); } });
jQuery插件不为某些元素提供函数,它们为jQuery对象提供函数以处理一组选定的元素。 最好的解决方案是尽可能保持通用,只在需要时调用$("textarea").maxHeight()
。 你没有对插件中的textarea
做任何特定的事情,如果你现在保留它,如果$('div').maxHeight()
变成了一个,你将来不需要对它进行更改$('div').maxHeight()
必需的用例。
你可以……
this.filter('textarea')
如果在返回的集合上执行each()
,它将仅迭代选定的textarea
元素。