admin管理员组

文章数量:1325367

I'm attempting to call a javascript function on a jQuery element that I created, but it seems that the function is not being called when run on a function. The function works when run on its own, but not when run on another jQuery object. Here is the function:

$(document).ready(function() {
var $Chart = $('#Chart');
/*
 returns true if some Expand element is open
*/
function closeExpand() {
    alert("Hello");
    /*$(this).css("background-color", "black");*/
};
});

It works when called on its own: /

$('.ChartLink').click(function() {
    closeExpand();
    });
});

But not when called on another jQuery object: /

$('.ChartLink').click(function() {
    $Chart.closeExpand();
    });
});

What am I doing wrong here, and how do I call a javascript function on another object?

I'm attempting to call a javascript function on a jQuery element that I created, but it seems that the function is not being called when run on a function. The function works when run on its own, but not when run on another jQuery object. Here is the function:

$(document).ready(function() {
var $Chart = $('#Chart');
/*
 returns true if some Expand element is open
*/
function closeExpand() {
    alert("Hello");
    /*$(this).css("background-color", "black");*/
};
});

It works when called on its own: http://jsfiddle/5F5GF/

$('.ChartLink').click(function() {
    closeExpand();
    });
});

But not when called on another jQuery object: http://jsfiddle/dsHRN/

$('.ChartLink').click(function() {
    $Chart.closeExpand();
    });
});

What am I doing wrong here, and how do I call a javascript function on another object?

Share Improve this question asked Dec 19, 2013 at 20:51 TimTim 7411 gold badge10 silver badges16 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

You could extend jquery.fn (jquery prototype) to add your new function, so that it is accessible from jquery object:

Try:

$.fn.closeExpand = function() {
   this.css("background-color", "black");
   return this; //for chaining
};
$Chart.closeExpand();

Demo

Your function closeExpand is not currently associated to the jquery object prototype, by adding it to its prototype you can invoke it with the jquery object.

Or you could do:

$('.ChartLink').click(function() {
    closeExpand.call($(this));
});

and

function closeExpand() {
   this.css("background-color", "black");
};

本文标签: Calling a javascript function on a jQuery objectStack Overflow