如何将 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 有 maxHeight 函数,但不是该分区。我怎样才能这样做呢?
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 );
Then, the div can have the maxHeight
method, like this:
var tallest = $('div').maxHeight(); // Returns the height of the tallest div
But I would like to only textarea have maxHeight function, but not the div. How can I do so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以做...
如果你对返回的集合执行
each()
,它只会迭代选定的textarea
元素。You could do...
If you do an
each()
on the returned set, it will only iterate over selectedtextarea
elements.在检查/保存高度之前检查并确保该元素是文本区域。
jQuery 插件不会为某些元素提供函数,而是为 jQuery 对象提供函数来处理一组选定的元素。最好的解决方案是使它们尽可能通用,并且仅在需要时调用
$("textarea").maxHeight()
。您没有在插件中执行任何特定于textarea
的操作,如果您保留现在的样子,则将来不需要对其进行更改,如果$( 'div').maxHeight()
成为必需的用例。Check to make sure the element is a textarea before checking/saving the height.
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 totextarea
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.