Reputation: 321
i'm writing a jQuery plugin and i met the following strange things:
$.fn.todo = function(options)
{
var $input = $("#main_body>input");
var $checkbox = $("#item_lists input:checkbox");
i define the instance here and quote it in this function(still in the plugin namespace) and it should be accessed isn't it?
$("#checkAll input").click(function()
{
$checkbox.prop("checked",this.checked);
});
...
the problem is that the $checkbox is not null ,but the length of the collection is 0. however when i put the definition in the click function like this:
$("#checkAll input").click(function()
{
var $checkbox = $("#item_lists input:checkbox");
$checkbox.prop("checked",this.checked);
});
i console.log the $checkbox.length ,and it shows that there are two elements. in addition,if i define a local function in the plugin namespace like this, the $checkbox is said to be undefined.
function dealWithCheckbox()
{
var checked_num = $checkbox.filter(":checked").length;
}
i wanna know where is the problem is.
Upvotes: 3
Views: 30
Reputation: 407
im guessing the plugin is getting initialized before the html has rendered, that's why it works on click, by that time the html has already been evaluated.
do you wrap you pluin in an jquery doc ready?
$(function(){
... my plugin code ...
})
Upvotes: 0
Reputation: 11725
This is happening because you're setting the variable in the begining, when there are no items yet.
Then, probably, you're dynamically adding items, but the variable is not updated automatically, since it's only an array with a reference to the elements found when the function was executed.
Each time you'll need to use the selector again, to get all the DOM changes that were made.
Upvotes: 1