Accessing jQuery object
I know this sounds pretty trivial, but I'm new to jQuery... I use this plugin: http://www.emposha.com/javascript/fcbkcomplete.html
Its source code contains:
jQuery(function ($) { $.fn.fcbkcomplete = function (opt) { return this.each(function () { /// ... /// ...implementation deleted... /// ... // public method to add new item this.addItem = function (title, value) { addItem(title, value); } return this; }); }; });
I know how to use this element in my code and it works fine:
$(document).ready(function() { $("#select2").fcbkcomplete({ ... options deleted ... }); });
N开发者_运维百科ow I want to call public method addItem() on the instance of the object "fcbkcomplete" created in my code (for example, when I click a button or from onTimer event). But I don't know how to access it. I tried to do it this way, but it does not work:
var fcel = $("#select2").fcbkcomplete({ ... options deleted ... }); fcel.addItem('Test1', 'Test1');
Firefox shows error: "fcel.addItem is not a function".
Thanx...
From your example, it looks like fcbkcomplete returns a jquery object (not a DOM element), as that is what this.each() returns.
The addItem method is added to individual elements ("this" within the each function refers to an individual element).
So in order to call addItem, you would have to refer to an individual element. Try:
fcel[0].addItem('Test1','Test1')
You have to add the elements to the list element used for the control (the control uses an input field and a list of elements).
Therefore you should add the elements to the UL.
(with something like $('#myUlId').append('<li>Hello</li>');
)
Cheers
jQuery allows you to access variables like this:
$(fcel).addItem('Test1', 'Test1');
Just stick your variable name in there without any quotes. Presto.
精彩评论