2

我正在创建一个 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>

如何在图标单击事件上获得对输入/文本区域的引用?self 指的是对象数组中的最后一个对象(在本例中为 textarea)

4

2 回答 2

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()
于 2013-07-28T08:10:13.273 回答
0

You can use the event object to get the target element.

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") )
});

you can get details over here

于 2013-07-28T07:48:13.187 回答