I have this link:
<%= link_to_function "remove", "remove_fields(this)"%>
which outputs this html:
<a href="#" onclick="remove_fields(this); return false;">remove</a>
and I hav开发者_如何转开发e this JQuery function:
function remove_fields(link){
$(link).prev("input[type=hidden]").val("1");
$(link).closest(".fields").hide();
}
but when I click on the link, I get this error:
Uncaught ReferenceError: remove_fields is not defined
Why is this and how do I fix it?
If you have your function declaration like this:
jQuery(function ($) {
function remove_fields ...
});
then it's only in scope inside the jQuery(function () { })
function and not visible from outside. Two methods of resolving this:
var remove_fields;
jQuery(function ($) {
remove_fields = function () { ... }
});
Declares a globally accessible variable and makes it a function as usual.
Better though:
jQuery(function ($) {
function remove_fields ...
$('a.some-class').click(remove_fields);
});
Attach the click handler programmatically from within your jQuery scope.
You should not use the onclick
attribute, it's a bad practice and something that belongs back in the 90s. Instead you should add a class for your anchors and bind a handler to the click event with jQuery.
HTML
<a class="remove-fields" href="#">remove</a>
JavaScript
// This is a shorthand for document.ready
$(function(){
// Bind handler to click event
$("a.remove-fields").click(function(e){
var $this = $(this);
$this.prev("input[type=hidden]").val("1");
$this.closest(".fields").hide();
// Prevent default behavior
e.preventDefault();
});
});
May be obvious, but is the javascript linked in the head in the source of the html?
精彩评论