2011-05-23 75 views
0

我有此鏈接:爲什麼我的應用程序告訴我我的方法未定義?

<%= link_to_function "remove", "remove_fields(this)"%> 

其輸出這個網站:

<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 

這是爲什麼?如何解決?

+1

何處以及如何被定義的功能? – deceze 2011-05-23 07:20:29

+0

在我的application.js文件中 – 2011-05-23 07:22:16

+0

它是在jQuery就緒語句之下嗎?嘗試從那裏移動它到公共範圍 – metaforce 2011-05-23 07:22:27

回答

1

你不應該使用onclick屬性,這是一個不好的做法,並且屬於90年代的東西。相反,您應該爲錨點添加一個類,並使用jQuery將處理程序綁定到click事件。

HTML

​​

的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(); 
    }); 
}); 
0

可能是顯而易見的,但是在HTML的源頭中鏈接的JavaScript是?

+0

是的,它是...... – 2011-05-23 07:24:04

2

如果你有你的函數聲明是這樣的:

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的範圍內,裝上單擊處理程序。

相關問題