简体   繁体   中英

Rails link_to ruby variable in onclick javascript

What is Wrong with this statement It is showing syntax error

<%= link_to image_tag('cancel.png'), {:action => 'remove', :id => question.id}, :title=>'Delete', :class=>'action', :onclick=>"removeQuestion("+ question.id +");return false;"%>

But

<%= link_to image_tag('cancel.png'), {:action => 'remove', :id => question.id}, :title=>'Delete', :class=>'action', :onclick=>"removeQuestion();return false;"%>

is correctly generating the below code

<a title="Delete" onclick="removeQuestion();return false" class="action remove" href="/quizzes/remove/1"><img src="/images/cancel.png?1290165811" alt="Cancel"></a>

What you wrote

<%= link_to image_tag('cancel.png'), {:action => 'remove', :id => question.id}, :title=>'Delete', :class=>'action', :onclick=>"removeQuestion("+ question.id +");return false;"%>

This bombs because question.id is a Fixnum. You would get can't convert Fixnum into String TypeError .

Ways to solve this

<%= link_to image_tag('cancel.png'), {:action => 'remove', :id => question.id}, :title=>'Delete', :class=>'action', :onclick=>"removeQuestion("+ question.id.to_s +");return false;"%>

OR

<%= link_to image_tag('cancel.png'), {:action => 'remove', :id => question.id}, :title=>'Delete', :class=>'action', :onclick=>"removeQuestion('#{question.id}');return false;"%>

This will send the question id as a string to your removeQuestion javascript function.

OR

<%= link_to image_tag('cancel.png'), {:action => 'remove', :id => question.id}, :title=>'Delete', :class=>'action', :onclick=>"removeQuestion(#{question.id});return false;"%>

This will send the question id as an integer to your removeQuestion javascript function.

 <%= link_to image_tag('cancel.png'), {:action => 'remove', :id => question.id}, :title=>'Delete', :class=>'action', :onclick=>"removeQuestion($(this).attr('id'));return false;"%>

这会奏效

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM