0
borrowed 나는 꽤 복잡한 JS 스톱워치를 가지고 있으며, 결과를 내 Rails 앱의 데이터베이스에보고하려고합니다. 나는 많은 유사한 SO posts을 상담했지만, 제대로 작동하지 못했습니다.자바 스크립트 변수를 레일에 전달 form_for hidden_field
<%= form_for @new_log do |f| %>
...
<div class="row text-center">
<div class="btn-white" id="startTime" style="display: inline-block;">
<h4 value="start" onclick="start();">Start Timer</h4>
</div>
<div style="display: inline-block;">
<span id="time" style="color: white"></span><br>
<span class="btn-white" value="reset" onclick="reset()">Reset</span>
</div>
<div class="btn-white" id="stopTime" style="display: inline-block;">
<h4 value="stop" onclick="stop();">Stop Timer</h4>
</div>
<%= f.hidden_field :duration, id: "duration" %>
...
<%= f.submit "Record My Log", id: "submit", class: "btn-ghost" %>
<% end %>
가 여기에 JS의 :
<script> // STOPWATCH
var clsStopwatch = function() {
// Private vars
var startAt = 0; // Time of last start/resume. (0 if not running)
var lapTime = 0; // Time on the clock when last stopped in milliseconds
var now = function() {
return (new Date()).getTime();
};
// Public methods
// Start or resume
this.start = function() {
startAt = startAt ? startAt : now();
};
// Stop or pause
this.stop = function() {
// If running, update elapsed time otherwise keep it
lapTime = startAt ? lapTime + now() - startAt : lapTime;
startAt = 0; // Paused
};
// Reset
this.reset = function() {
lapTime = startAt = 0;
};
// Duration
this.time = function() {
return lapTime + (startAt ? now() - startAt : 0);
};
};
var x = new clsStopwatch();
var $time;
var clocktimer;
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';
h = Math.floor(time/(60 * 60 * 1000));
time = time % (60 * 60 * 1000);
m = Math.floor(time/(60 * 1000));
time = time % (60 * 1000);
s = Math.floor(time/1000);
ms = time % 1000;
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
return newTime;
// THIS IS THE PART I ADDED, WHICH IS NOT WORKING
$('#submit').on('click', function() {
$('#duration').val(newTime);
});
// MY ADDITION ENDS HERE
}
function show() {
$time = document.getElementById('time');
update();
}
function update() {
$time.innerHTML = formatTime(x.time());
}
function start() {
clocktimer = setInterval("update()", 1);
x.start();
}
function stop() {
x.stop();
clearInterval(clocktimer);
}
function reset() {
stop();
x.reset();
update();
}
</script>
는 희망이 나보다 JS을위한 더 나은 눈을 가진 사람을위한 아주 간단한 수정 될 것입니다
여기 내 ERB입니다. 현재 스톱워치 및 양식 제출은 계속 작동하지만 :duration
은 여전히 nil
으로 데이터베이스에 기록됩니다.
도움을 주셔서 감사합니다.
'var newTime'으로 변경하고 함수 외부에서 onclick val 변경을 시도했지만 여전히 'nil'이었습니다. 리턴 바로 전에 onclick을 시도했고 값은 newTime의 값과 관계없이 '0'이었습니다. 생각? – Liz
newTime을 반환하기 직전에'console.log (newTime);'을 넣는 것은 스톱워치의 내용에 상관없이'00 : 00 : 00 : 000' 값을 보여줍니다. 이 도움이 중요합니까? – Liz