Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

variable in jQuery plugin

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.

like image 989
lizlalala Avatar asked Nov 24 '25 18:11

lizlalala


1 Answers

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.

like image 192
Buzinas Avatar answered Nov 26 '25 07:11

Buzinas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!