我想在单击Rails表单中的按钮时调用JS函数。该函数在下面的.js.erb
文件中定义。
当我点击按钮时,chrome的JS控制台会抛出以下错误:
Uncaught ReferenceError: logTime is not defined
我知道这意味着它无法找到该功能,但我不明白为什么。特别是因为我在文件中添加了<%= javascript_include_tag "track.js.erb" %>
。有任何想法吗?
如果这是一个noob问题,请提前告别,但我的Google-fu没有结果。
_track_time_form.html.erb
<div id="countdown-timer"></div>
<div id="playback-button">►</div>
<div id="track-time-form">
<%= form_for @project, :url => { :action => "log_time" }, remote: true do |p| %>
<ul>
<li><%= p.label :project, "Project:"%><br>
<%= p.collection_select(:id, current_user.projects, :id, :name) %></li>
<%= p.hidden_field :time_logged, :value => 0 %> <!-- value set by script in log_time.js.erb -->
<li><%= p.submit "Log time", id: "log-time-button", :onclick => "logTime()" %></li>
</ul>
<% end %>
</div>
处理程序调用的函数可以在这里找到:
track.js.erb
//initialise form
timeTrackingForm = window.open("", "", "height=700,width=500");
$(timeTrackingForm.document.body).html("<%= j render( :partial => 'track_time_form' ) %>");
//assign variables
var timer = $("#countdown-timer", $(timeTrackingForm.document));
var playbackControls = $("#playback-button", $(timeTrackingForm.document));
var form = $("#track-time-form", $(timeTrackingForm.document));
var formUl = $("#track-time-form ul", $(timeTrackingForm.document));
var formLi = $("#track-time-form li", $(timeTrackingForm.document));
var logTimeButton = $("#log-time-button", $(timeTrackingForm.document));
var timerPaused;
//initialise timer
$(timeTrackingForm.document).ready(function(){
initialiseTimer();
style();
$(playbackControls).click(function() {
playOrPause();
});
});
function initialiseTimer() {
$(timer).timer({
format: '%H:%M:%S'
});
$(timer).timer('pause');
timerPaused = true;
}
function style() {
$(timer).css({'color':'black','font-size':'50px', 'margin':'auto', 'width':'180px'});
$(playbackControls).css({'color':'#290052', 'font-size':'50px', 'margin':'auto', 'width':'55px'});
$(form).css({'width':'300px','margin':'auto'});
$(formUl).css({'list-style-type':'none'});
$(formLi).css({'margin':'0 0 25px 0','font-sizeL':'18px','font-family':'Arial'});
$(logTimeButton).css({'width':'180px','font-size':'18px','background-color':'green','color':'white','margin-top':'15px'});
}
function playOrPause() {
if (timerPaused == true) {
$(timer).timer('resume');
timerPaused = false;
}
else {
$(timer).timer('pause')
timerPaused = true;
}
}
function logTime() {
$(timer).timer('pause');
var secondsTracked = $(timer).data('seconds');
$('input:hidden').val(secondsTracked);
$('#countdown-timer').timer('reset');
}
答案 0 :(得分:0)
对于任何对该解决方案感兴趣的未来读者,请参阅以下问题(非常感谢上面有用的评论者)。
我在 track.js.erb 中为表单添加了一个事件监听器,当单击该按钮时(但在表单实际提交并向控制器发送数据之前)会触发该事件监听器。这是:
var actual_form = $("#new_project", $(timeTrackingForm.document));
$(actual_form).submit(function(){
$(timer).timer('pause');
timerPaused = true;
var secondsTracked = $(timer).data('seconds');
$(hidden).val(secondsTracked);
resetTimerDisplay();
});