簡體   English   中英

Rails link_to onclick javascript中的ruby變量

[英]Rails link_to ruby variable in onclick javascript

什么是錯誤的這句話它顯示語法錯誤

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

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

正確生成以下代碼

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

你寫的是什么

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

這是炸彈,因為question.id是一個Fixnum。 您將can't convert Fixnum into String TypeError

如何解決這個問題

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

要么

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

這會將問題ID作為字符串發送到您的removeQuestion javascript函數。

要么

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

這會將問題ID作為整數發送到您的removeQuestion javascript函數。

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

這會奏效

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM