【问题标题】:How to use jQuery extend method to create a custom plugin for element or class selectors如何使用 jQuery 扩展方法为元素或类选择器创建自定义插件
【发布时间】:2016-04-14 04:05:36
【问题描述】:

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

我真正想要的是为用户提供如何使用 jQuery 扩展 $fn 的示例。创建自定义插件。虽然不是一个理想的用法,但这个例子很简单,因为用户只需使用基于类名的选择器传入某种值(最小值或最大值或两者?),然后插件会自动更新元素 max-length/min-长度和长度值)。

这是我目前所拥有的,但我知道我还没有走在正确的轨道上。或者更好的是,还创建另一个插件来设置min-length、max-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); //更喜欢这个,因为我想这就是我想使用它的方式?

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


编辑

这是我找到的最简单的例子,但这只是一个扩展对象的指标/变量,而不是 jQuery/js 对象的方法:

$(document).tooltip.temporarilyOff 那么当我初始化jQuery tooltip的时候,我只需要在open中添加一个check:

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;

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

$.fn.greenify = function() {
    this.css( "color", "green" );
};

$( "a" ).greenify(); // Makes all the links green.

【问题讨论】:

  • 为什么不用输入maxlength?不用js也可以做到
  • 检查这可能是你想要的jsfiddle.net/jznxtgm0
  • 使用 keyup 代替看到这个jsfiddle.net/jznxtgm0/1
  • 对于 A:$('input').attr('maxlength', 2) 对于 B:参见演示
  • 更多的是关于我学习增加 jQuery 对象的功能。

标签: javascript jquery jquery-selectors


【解决方案1】:

给你:

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

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

Codepen:http://codepen.io/nobrien/pen/MyVRXd

【讨论】:

  • 请赐教,当您可以使用输入的最大长度属性时,为什么要创建一个限制用户输入的功能?
  • 因为原发帖人说他想通过这个练习了解jquery。我同意 maxlength 是解决该确切问题的首选解决方案,但作为一个学习练习,捕获击键、将事件应用于类、读取数据属性和防止事件操作都包含在此问题中。那为什么不呢?
  • 不,我指的是 OP 我指的是你为什么要制作那个。说明为什么要创建函数而不是使用 maxlength。
  • 因为这是发帖人要求的。使用 maxlength 并不能满足发帖者对 jQuery 了解更多的要求。
  • 注意:isNan() 确实允许十六进制和其他带有字母数字的数字,所以如果可以,我添加到您的答案中?
猜你喜欢
  • 2014-04-03
  • 1970-01-01
  • 2017-02-20
  • 2021-09-05
  • 1970-01-01
  • 1970-01-01
  • 2011-01-14
  • 1970-01-01
相关资源
最近更新 更多