在jQuery中绑定现有的JavaScript函数
使用jQuery我想将现有函数绑定到按钮。 我已经浏览了文档并找到了bind方法,但是jQuery上的示例绑定了新创建的函数,因为我想绑定一个已经硬编码的函数,例如:
function fHardCodedFunction(){ //Do stuff } function fBindFunctionToElement(){ $("#MyButton").bind("click", fHardCodedFunction()); }
这可能吗? 或者我是以错误的方式来做这件事的?
普通的fHardCodedFunction
已经引用了函数,后缀()
只会调用它。 所以只需传递函数而不是调用它,从而只传递返回值:
function fBindFunctionToElement(){ $("#MyButton").bind("click", fHardCodedFunction); }
借用其他post,您可以按如下方式参数化您的事件处理程序:
function fHardCodedFunction(someValue) { alert(this.id + " - " + someValue); } function fBindFunctionToElement() { var someValue = "whatever"; $("#MyButton").bind("click", function() { fHardCodedFunction.apply(this, [someValue]); } ); } $(document).ready ( function() { fBindFunctionToElement(); } );
我在这里使用apply因为在函数fHardCodedFunction
我想要this
属性来引用MyButton
元素。 另请注意,apply需要第二个参数的数组,这就是为什么我在括号中包含了someValue
。
您不必这样做,如果您愿意,可以完全忘记this
属性。
是的,您可以绑定写在其他地方的方法,但是您应该忽略括号:
function fHardCodedFunction(){ //Do stuff } function fBindFunctionToElement(){ $("#MyButton").bind("click", fHardCodedFunction); }