我正在
Ruby on Rails中编写一个表单,并希望有一个调用
Javascript函数的选择框.在表单文件中,这是我用来尝试添加选择框的行:
<%= f.select :question_select,Question.all,:prompt => "New Question",:onchange => "displayQuestion(this)" %>
在我的application.js文件中,我只有:
function displayQuestion(link) { alert("Changed question"); }
我将动态地将这些表单元素添加到页面中,因此我不能在application.js文件中使用jQuery将函数添加到特定的表单元素.谁能告诉我我做错了什么?
解决方法
您可能知道,Rails 3强烈鼓励UJS(不引人注目的JavaScript),这基本上意味着JavaScript完成了繁重的工作,并且您不应该将您的客户端交互性与表单生成器联系起来.我建议在这里做一些非常相似的事情 – 只是因为你动态添加元素并不意味着你不能使用jQuery来监视它们的变化.
在您的模板中:
<%= f.select :question_select,{prompt: "New Question"},data: { question: true } %>
这会产生如下内容:
<select id="..." data-question="true"> ... </select>
然后,在JavaScript中,您可以使用事件委派来监视任何元素上的更改事件,并在整个文档上设置数据问题:
$(function() { $(document).on('change','[data-question]',function() { // this == the element that fired the change event alert('Changed question'); }); });
注意:您可以简单地向元素添加一个类,然后修改您的jQuery以使用该类,而不是使用数据问题:
$(function() { $(document).on('change','.question',function() { // this == the element that fired the change event alert('Changed question'); }); });
我通常会尝试在我的JavaScript中最小化CSS选择器的使用,以便设计人员可以自由地将它们更改为他们想要的任何内容而不会破坏事物,但它也可以正常工作.