最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Calling a javascript function on a jQuery object - Stack Overflow

programmeradmin1浏览0评论

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");
};
发布评论

评论列表(0)

  1. 暂无评论