2013-07-28 23 views
2

我正在创建一个jquery插件,它在被调用的元素旁添加一个帮助文本图标。我如何获得对调用插件方法的原始输入/ textarea对象的引用?如何保持对引用jquery插件的原始对象的引用?

下面是代码:

<input text name="name" data-help-text="Enter your name here" class="helpon"> 
    <input text name="age" data-help-text="Enter your age here" class="helpon"> 
    <textarea name="experience" data-help-text="Enter a short summary of your experience" class="helpon"> </textarea> 


    <script type="text/javascript"> 
    $(document).on("ready", function() { 

     $.fn.showHelp = function() { 
      return this.each(function() { 
       self = $(this) 
       var icon = $('<icon class="icon-question" data-help-text="icon here">?</i>') 
       icon.on("click", function(){ 
       //how do i get a reference to the input/textarea here on which this? 
        alert(self.data("help-text")) 
       }); 
       self.after(icon); 
      }); 
     }; 


     $('.helpon').showHelp(); 
    }); 


    </script> 

如何获得上的图标click事件的参考输入/ textarea的? self指的是对象数组中的最后一个对象(本例中为textarea)

回答

1

你需要给一个范围的self变量就可以得到详细信息:

$.fn.showHelp = function() { 
      return this.each(function() { 
       var self = $(this) 
       var icon = $('<icon class="icon-question" data-help-text="icon here">?</i>') 
       icon.on("click", function(){ 
       //how do i get a reference to the input/textarea here on which this? 
        alert(self.data("help-text")) 
       }); 
       self.after(icon); 
      }); 
     }; 


     $('.helpon').showHelp() 
+0

我该怎么做?不确定你的回答如何? – thanikkal

+0

我刚刚在''var''关键字中声明'self',就在你的每个函数中。这将限制自我的范围到每个循环 – CodingIntrigue

+0

真棒!我现在明白了。谢谢 :) – thanikkal

0

您可以使用事件对象来获取目标元素。

var icon = $('<icon class="icon-question" data-help-text="icon here">?</i>') 
icon.on("click", function(){ 
    // you can use the target of the event object 
    alert($(e.target).data("help-text")) 
}); 

here

+0

这是行不通的,电子仍然是指图标元素。 – thanikkal

相关问题