Plugin - get reference to passed object
i'm trying to create my first jQuery plugin. i got a prototype function called myListview and want to apply the plugin (named initLV) to it.
the function:
function myListview(div)
{
this.div = div;
$(this).initLV(); // apply the plugin
}
as you can see, i'm passing the whole prototype object to the plugin. my question: how can i access the object's div from inside the plugin? here's my plugin code - the 1st alert works, but all others dont :/
(function ($) {
$.fn.initLV = function ()
{
alert($("tr",this.div).length); // works
alert(this.div.html()); // don't work
alert($(this.div).html()); // don't work
alert($(this).div.html()); // don't work
}
})(jQuery);
it just makes no sense that the 1st alert works and the others don't. what could be 开发者_JS百科wrong?
I think div
is only a field of what the this
is. What div
contains. If it contains an html element, so for instance you should use alert($(this[0].div).html());
instead. But it's better to use Dan Herbert's answer that demonstrates the correct way of writing a plugin.
I think you're a bit confused with how jQuery plugins work. A jQuery plugin allows you to perform actions on a jQuery object. It looks like your code creates a custom object, and then tries to "jQuery-ify" it. I don't think your first function even works as valid jQuery. I think it just happens to work because jQuery is good about ignoring invalid arguments.
It would help if I knew what your ultimate end goal was, however I think you might want to try something like this instead:
Your function:
function myListview(div)
{
$(div).initLV();
}
Your plugin
(function ($) {
$.fn.initLV = function () {
// "this" will be a jQuery object storing your
// div, or whatever else the jQuery object
// contains when it gets called.
alert($("tr", this).length); // works
alert(this.html()); // works
alert(this.find("tr").html());// works
}
})(jQuery);
精彩评论