jQuery:如何将$(this)作为插件参数发送

jQuery:如何将$(this)作为插件参数发送,jquery,plugins,parameters,this,Jquery,Plugins,Parameters,This,我创建了一个jQuery插件来管理输入内容(max chars、preg match等)。我想这样使用它: $("form textarea.count-chars").smartInput({ counterDiv: "#" + $(this).attr("id") + "-chars-left", maxChars: 128 }); 这意味着,该插件使用类“count chars”获取所有textarea,并在div块中显示一个倒计时字符,其id与对应的textarea

我创建了一个jQuery插件来管理输入内容(max chars、preg match等)。我想这样使用它:

$("form textarea.count-chars").smartInput({

    counterDiv: "#" + $(this).attr("id") + "-chars-left",
    maxChars: 128

});
这意味着,该插件使用类“count chars”获取所有textarea,并在div块中显示一个倒计时字符,其id与对应的textarea+“-chars left”相同。这里的问题是

console.log显示$(this).attr(“id”)指未定义的

那么:如何使用输入的属性(例如)作为插件参数呢

以下是插件:


提前谢谢。

您不能在那里设置此


只有在回调中。

我现在唯一能想到的就是使用
.each()

之所以在显示的代码中未定义
$(this).attr(“id”)
,是因为此时
this
与jQuery“form textarea.count chars”选择器无关,因此
this
不是正在处理的“当前”元素<首先计算code>$(this).attr(“id”)
(以及该对象文字的其余部分),并将结果传递给插件

如果需要检索每个匹配元素的某些属性,则需要在插件中执行。或者将插件设置为获取另一个参数,即回调函数,然后可以提供一个函数以某种方式处理各个元素

以下是如何做的粗略概述:

(function( $ ) {
  $.fn.smartInput = function(options) {      
     this.each(function() {
        // get associated div's id via the supplied callback,
        // passing the current element to that callback            
        var associatedDivId = options.callback.call(this,this);

        // do something with the id
     });    
  };
})( jQuery );


$(("form textarea.count-chars").smartInput({
   maxChars : 128,
   callback : function(el) { return $(this).attr("id"); }
});

测试和批准。非常感谢你的贡献。非常感谢你的解释。但使用函数回调似乎有点棘手!Phil的解决方案似乎更简单(使用和保持插件的原样)。在所有情况下,我都需要更深入地挖掘$(此)使用。再次感谢,不客气。我想我假设您不想使用
.each()
一次调用一个元素来调用插件,因为插件通常设计为处理多个元素。另一种实现方法是在输入中添加
data chars left id
属性,并在标记中指定关联的id-然后插件可以从那里简单地读取id,而不是将其作为参数/选项-您可以对
maxChars
执行相同的操作,然后您对插件的调用将是
$(“form textarea.count chars”).smartInput()然后它会找出剩下的。
(function( $ ) {
  $.fn.smartInput = function(options) {      
     this.each(function() {
        // get associated div's id via the supplied callback,
        // passing the current element to that callback            
        var associatedDivId = options.callback.call(this,this);

        // do something with the id
     });    
  };
})( jQuery );


$(("form textarea.count-chars").smartInput({
   maxChars : 128,
   callback : function(el) { return $(this).attr("id"); }
});