我正在尝试在 C9 上的 Rails 应用程序中使用 JS 编写个性测验代码,但我似乎无法让 JavaScript 工作。我写了几个测试测验,但没有一个起作用。下面是一个示例的副本,该示例适用于 JSfiddle,但不适用于我的应用程序:
javascript 位于 asset 的 javascripts 文件夹中名为 rec 的文件中:
var form = document.forms.survey
function getValues () {
// add your <input> names to this array:
return [
'bee',
'camel',
'eagle'
].reduce(function (obj, cur) {
var input = form[cur]
obj[cur] = input.checked ? Number(input.value) : 0
return obj
}, {})
}
function computeResults (values) {
// adjust your equation here:
return values.bee + values.camel*2 - values.eagle
}
// show the result in the DOM
function showResults (total) {
document.querySelector('#total').innerHTML = total
}
// when the form is submitted, compute and show the result
document.getElementsByName('survey')[0].addEventListener('submit', function (event) {
event.preventDefault() // prevent the browser from redirecting the page
showResults(computeResults(getValues()))
})
以及 View 中的 html:
<form name="survey">
What is your favorite animal?
<label>
<input type="checkbox" name="bee" value="1" />
Bee
</label>
<label>
<input type="checkbox" name="camel" value="1" />
Camel
</label>
<label>
<input type="checkbox" name="eagle" value="1" />
Eagle
</label>
<input type="submit" value="Go!" id="submit" />
Total is: <span id="total"></span>
</form>
最佳答案
正如评论中提到的,您需要将 Javascript 包装在文档就绪函数中。
请记住,rails 默认情况下包含 Turbo 链接,这会导致与文档就绪相关的一些意外行为。搜索堆栈溢出以了解如何将两者一起使用。我确信那里有很多教程。
关于javascript - Rails 应用程序 C9 中的 JavaScript 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38083256/