Reputation: 10350
The following link_to_function works:
<%= link_to_function "click", "alert(Hallo world!" %>
However, with jquery, the following does not work:
<%= link_to_function "click", "$('#std').append('<p>my friend!</p>')" %>
In application.html.erb, there are:
<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 seems functioning well. Any thoughts about the problem? Thanks.
Also here is the api definition in rails 3.1.3 for link_to_function:
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>
UPDATE: here is the html sour code:
<a href="#" onclick="$('#std').append('<p>my friend!</p>'); return false;">test</a>
Upvotes: 2
Views: 2089
Reputation: 7899
That is the obtrusive way to write javascript. I would write something like this:
<%= link_to "click", "#", :id=>"click" %>
Update
You should add document ready to have the proper binding.
Then in your application.js
$(function() {
$("#click").click(function(e){
$('#std').append('<p>my friend!</p>');
e.preventDefault();
});
});
Upvotes: 7
Reputation: 3137
are you using prototype too? if not then following code should work. add this in your view.
<%= link_to "click", "javascript:", :onclick => "call_function();" %>
in your script file add following code.
function call_function () {
$('#std').append('<p>my friend!</p>');
}
Upvotes: 1