以下link_to_function有效:
<%= link_to_function "click", "alert(Hallo world!" %>
但是,使用jquery,以下内容不起作用:
<%= link_to_function "click", "$('#std').append('<p>my friend!</p>')" %>
在application.html.erb中,有:
<head>
<title><%= title %></title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<%= stylesheet_link_tag "application" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
</head>
jquery似乎运作良好。有关这个问题的任何想法?感谢。
此处还有rails 3.1.3中关于link_to_function的api定义:
link_to_function(name, function, html_options={})
Returns a link whose onclick handler triggers the passed JavaScript.
The helper receives a name, JavaScript code, and an optional hash of HTML options. The name is used as the link text and the JavaScript code goes into the onclick attribute. If html_options has an :onclick, that one is put before function. Once all the JavaScript is set, the helper appends “; return false;”.
The href attribute of the tag is set to “#” unless html_options has one.
link_to_function "Greeting", "alert('Hello world!')", :class => "nav_link"
# => <a class="nav_link" href="#" onclick="alert('Hello world!'); return false;">Greeting</a>
更新:这是html酸代码:
<a href="#" onclick="$('#std').append('<p>my friend!</p>'); return false;">test</a>
答案 0 :(得分:7)
这是写javascript的突兀方式。我会写这样的东西:
<%= link_to "click", "#", :id=>"click" %>
<强>更新强>
您应该准备好文档,以便具有正确的绑定。
然后在你的application.js
中$(function() {
$("#click").click(function(e){
$('#std').append('<p>my friend!</p>');
e.preventDefault();
});
});
答案 1 :(得分:1)
<%= link_to "click", "javascript:", :onclick => "call_function();" %>
在脚本文件中添加以下代码。
function call_function () {
$('#std').append('<p>my friend!</p>');
}