jQuery 插件 Return this.each 并向每个对象添加函数 属性?

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

是否可以创建一个 jQuery 插件,returns 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 ));

然后我想在 document.ready 函数中调用这个:

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

这可能吗?我收到一条错误消息,指出 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" />

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

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