如何将 jQuery 插件功能限制为仅某些元素? [英] How to limit a jQuery plugin function to only some elements?
问题描述
我查看了 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 textarea
s 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 插件功能限制为仅某些元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!