jQuery插件返回this.each并为每个对象添加函数属性

jQuery Plugin Return this.each and add function property to each object?

本文关键字:对象 添加 函数 属性 返回 插件 this each jQuery      更新时间:2024-01-03

是否可以创建一个jQuery插件,为多个匹配返回this.each,从而允许我为每个循环中的每个对象添加一个函数属性?我想稍后直接从对象中调用此函数。

例如,下面是我尝试做的事情的简化版本:

(function ( $ ) {
  $.fn.roflcopter = function( options ) {
    return this.each(function() {
        $(this).addClass('lol');
        $(this).getMyValue = function(e){
            return returnMyFilteredValue($(this));
        }
    });
    function returnMyFilteredValue(elem){
        return $(elem).val().replace("cat", "dog");
    }
  };
}( jQuery ));

然后我想在一个文档中。ready函数调用这个:

$("input.coolStuff").roflcopter();
var value = $("input.coolStuff").first().getMyValue();

这可能吗?我收到一个错误,指出getMyValue不是一个函数。

小改动:只需将getMyValue放在"this"上,而不是放在$(this)上,然后通过访问它

$("input.coolStuff").first()[0].getMyValue()

您可以使用.data()在元素中存储和调用函数;Function.prototype.bind()getMyValue 处在.each()内将this设置为$(this)

$(function() {
  (function($) {
    $.fn.roflcopter = function(options) {
      return this.each(function() {
        $(this).addClass("lol");
        function getMyValue(e) {
          return returnMyFilteredValue(this);
        };
        $(this).data().getMyValue = getMyValue.bind($(this));
      });
      function returnMyFilteredValue(elem) {
        return elem.val(function(index, val) {
          return val.replace("cat", "dog");
        })
      }
    };
  }(jQuery));
  $("input.coolStuff").roflcopter();
  var value = $("input.coolStuff").first().data().getMyValue();
  console.log(value, value.val())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input class="coolStuff" value="cat" />
<input class="coolStuff" value="cat" />