JQuery - Object [object Object]没有方法

Rok*_*ius 3 javascript jquery function

您好我正面临这个奇怪的JQuery问题.我的Js:

$("#flip-counter").centerH();
function centerH() {
var marginL = ( $(window).width() - $(this).width() ) / 2;
$(this).css("marginLeft",marginL+"px");
alert(marginL);
}
Run Code Online (Sandbox Code Playgroud)

得到此错误:

Uncaught TypeError: Object [object Object] has no method 'centerH'         
(anonymous function) 

k jquery.js:2 
l.fireWith jquery.js:2 
p.extend.ready jquery.js:2
D jquery.js:2
Run Code Online (Sandbox Code Playgroud)

jquery.js:2为空.

我会理解,如果没有任何代码可以工作,但现在一切正常,除了那个,我不能添加任何其他功能.我只是不断得到同样的错误.正确包含所有文件,当我删除这段JS代码时,我的代码就像一个魅力.

有什么建议?

Dáv*_*abó 6

如果要将该函数与jquery对象一起使用,则需要扩展jquery.

$.fn.centerH = function() {
    var marginL = ( $(window).width() - $(this).width() ) / 2;
    $(this).css("marginLeft",marginL+"px");
    alert(marginL);
}
Run Code Online (Sandbox Code Playgroud)