3

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.

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

u'r right!but each time i have to update it manually just like define a new variable and use the selector? is there any other solutions?
You can use the same variable if you want, but you need to update it each time, there is no workaround to this. You can read about Mutation Observers, but it's too much work for something like that.
@lizlalala Btw, if my answer was useful to you, please click on the arrow to upvote it, and - if possible - click on the V to mark it as the accepted one.
0

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 ...
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.