我有这个链接:
<%= link_to_function "remove", "remove_fields(this)"%>
输出这个html:
<a href="#" onclick="remove_fields(this); return false;">remove</a>
我有这个 JQuery 函数:
function remove_fields(link){
$(link).prev("input[type=hidden]").val("1");
$(link).closest(".fields").hide();
}
但是当我单击链接时,出现此错误:
Uncaught ReferenceError: remove_fields is not defined
这是为什么?如何解决?
最佳答案
如果您的函数声明如下:
jQuery(function ($) {
function remove_fields ...
});
那么它仅在 jQuery(function () { })
函数内部的范围内,从外部不可见。解决此问题的两种方法:
var remove_fields;
jQuery(function ($) {
remove_fields = function () { ... }
});
声明一个全局可访问的变量并使其像往常一样成为一个函数。
不过更好:
jQuery(function ($) {
function remove_fields ...
$('a.some-class').click(remove_fields);
});
在 jQuery 范围内以编程方式附加点击处理程序。
关于javascript - 为什么我的应用程序告诉我我的方法未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6094045/