如何使用jQuery扩展方法为元素或类选择器创建自定义插件

How to use jQuery extend method to create a custom plugin for element or class selectors

本文关键字:选择器 创建 自定义 插件 元素 jQuery 何使用 扩展 方法      更新时间:2024-06-10

试图提高我的jQuery/javascript技能,我认为我遇到了一个完美的问题,这可能会帮助我学习如何以及何时使用扩展方法来处理jQuery对象。我基本上是在尝试创建一个函数来限制input[type=text]元素的最大长度。

我真正想要的是,这将成为用户如何使用jQueryextend$fn的一个示例。创建自定义插件。虽然这不是一个理想的用法,但这个例子很简单,因为用户只需根据类名使用选择器输入某种值(最小值或最大值或两者都有?),然后插件会自动更新元素(最大长度/最小长度和长度值)。

这就是我目前所拥有的,但我知道我还没有走上正轨。或者更好的是,还可以创建另一个插件,设置min-length、最大长度和length属性。请随时根据需要进行编辑。提前感谢!

<script>
maxLength(length,element) {
        if (element.val().length <= length) { 
            return false;
        } else {
            return true;
        }
}
$(".max-length").keypress(function (element) {
    maxLength(2,element);
});
</script> 

我想要的是我可以

A: $("Textbox).maxLength(2);//更喜欢这个,因为我想这就是我想要的使用方式?

B: maxLength($("#Textbox"), 2);


编辑

以下是我发现的一些隐秘的例子,但这只是一个扩展对象的指示符/变量,而不是jQuery/js对象的方法:

$(document).tooltip.temporaryOff然后,当我初始化jQuery工具提示时,我只需要在打开的中添加一个复选框

var settings = {};
settings.tooltipClass = "tooltip";
settings.open = function (event, ui) {
    if ($(document).tooltip.temporarilyOff) {
        ui.tooltip.stop().remove();
    }
};
$(document).tooltip(settings);
//set the variable of the object 
$(document).tooltip.temporarilyOff = true;

搞砸的是,我想我不知道我在找的是一个插件。Doh!jQuery文档一直都有我的例子。我想现在只剩下args的通过了

$.fn.greenify = function() {
    this.css( "color", "green" );
};
$( "a" ).greenify(); // Makes all the links green.

开始:

我扩展了该解决方案,从数据属性中提取最大长度,因此它对您来说更灵活。

<input type="text" class="max-length" data-maxlength="5"> <input type="text" data-maxlength="3" class="max-length" />
<script type="text/javascript">
    //https://learn.jquery.com/plugins/basic-plugin-creation/
(function( $ ) { //Protect the $ Alias and Adding Scope
  $.fn.restrictLength = function(lengthVal) {
      //This plugin will work for all the elements that match the selector
      return this.each(function() {
        //Capture the keypress event and evaluate the input value length
        $(this).keypress(function(e) {
          //Make sure the data attribute is a number, else allow unrestricted max value
          //prevents hex and other number with alphas
          this.value = this.value.replace(/[^0-9.]/g,'');
          var dataMax = !isNaN($(this).data('maxlength')) ? $(this).data('maxlength') : ($(this).val().length+1);
          //Use the passed in value if it exists, if not use the data attribute (if it exists and is a nummber), else make it longer than the current value (not restricted)
         var length = !isNaN(lengthVal) ? lengthVal : dataMax;
         if ($(this).val().length >= length) { 
           //String is too long, don't execute the event
            return false;
          } else {
            //String length is good, allow the keyPress event to continue
            return true;
          }
        });
      });
  };
}( jQuery ));

$(document).ready(function() {
 // $(".max-length").restrictLength(4);  //Restrict all fields to 4 characters
  $(".max-length").restrictLength();  //Each field will be restricted to its data attribute value
})
</script>

代码笔:http://codepen.io/nobrien/pen/MyVRXd