How to limit a jQuery plugin function to only some elements?

后端 未结 2 1960
情书的邮戳
情书的邮戳 2021-01-22 20:42

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

(function( $ ){
  $.fn.maxHeight = function() {
    var max = 0;
    this.each(functi         


        
相关标签:
2条回答
  • 2021-01-22 21:26

    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 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.

    0 讨论(0)
  • 2021-01-22 21:28

    You could do...

    this.filter('textarea')
    

    If you do an each() on the returned set, it will only iterate over selected textarea elements.

    0 讨论(0)
提交回复
热议问题