在jQuery对象上调用javascript函数

时间:2013-12-19 20:51:22

标签: javascript jquery html css

我试图在我创建的jQuery元素上调用javascript函数,但似乎在函数上运行时没有调用该函数。该函数在单独运行时有效,但在另一个jQuery对象上运行时则无效。这是功能:

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

单独调用时可以正常工作:http://jsfiddle.net/5F5GF/

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

但是在调用另一个jQuery对象时却没有:http://jsfiddle.net/dsHRN/

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

我在这里做错了什么,如何在另一个对象上调用javascript函数?

1 个答案:

答案 0 :(得分:5)

您可以扩展jquery.fn(jquery prototype)来添加新函数,以便可以从jquery对象访问它:

尝试:

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

<强> Demo

您的函数closeExpand当前未与jquery对象原型相关联,通过将其添加到其原型,您可以使用jquery对象调用它。

或者你可以这样做:

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

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