如何在Ruby on Rails中为表单元素添加onchange监听器? [英] How to add an onchange listener for form elements in Ruby on Rails?

查看:213
本文介绍了如何在Ruby on Rails中为表单元素添加onchange监听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Ruby on Rails中编写一个表单,并希望有一个调用Javascript函数的选择框。在表单文件中,这是我用来尝试添加选择框的行:

I am writing a form in Ruby on Rails and want to have a select box that calls a Javascript function. In the form file, this is the line I am using to try to add the select box:

<%= f.select :question_select, Question.all, :prompt => "New Question", :onchange => "displayQuestion(this)" %>

在我的application.js文件中,我只有:

In my application.js file, I just have:

function displayQuestion(link) {
    alert("Changed question");
}

我将动态地将这些表单元素添加到页面中,所以我不能只在application.js文件中使用jQuery来向特定表单元素添加函数。谁能告诉我我做错了什么?

I am going to be dynamically adding these form elements to a page, so I can't just use jQuery in the application.js file to add a function to a specific form element. Can anyone tell me what I'm doing wrong?

推荐答案

您可能知道,Rails 3强烈鼓励UJS(不显眼的JavaScript) ,这基本上意味着JavaScript完成了繁重的工作,并且您不应该将您的客户端交互性与表单生成器联系起来。我建议在这里做一些非常相似的事情 - 只是因为你动态添加元素并不意味着你不能使用jQuery来监视它们的变化。

As you may know, Rails 3 strongly encourages UJS (unobtrusive JavaScript), which basically means that the JavaScript does the heavy lifting, and that you shouldn't tie your client-side interactivity in with your form generators. I would recommend doing something very similar here--just because you're adding elements dynamically doesn't mean you can't use jQuery to watch for changes on them.

在您的模板中:

<%= f.select :question_select, Question.all, {prompt: "New Question"}, data: { question: true } %>

这会产生以下内容:

<select id="..." data-question="true">
  ...
</select>

然后,在JavaScript中,您可以使用事件委派来监听更改在整个文档上设置 data-question 的任何元素上的事件:

Then, in JavaScript, you can use event delegation to watch for change events on any element with data-question set on the entire document:

$(function() {
  $(document).on('change', '[data-question]', function() {
    // this == the element that fired the change event
    alert('Changed question');
  });
});






注意:而不是使用 data-question ,您可以简单地向该元素添加一个类,然后修改您的jQuery以使用该类:


Note: Instead of using data-question, you could simply add a class to the element, and then modify your jQuery to use that class:

$(function() {
  $(document).on('change', '.question', function() {
    // this == the element that fired the change event
    alert('Changed question');
  });
});

我通常会尽量减少在我的JavaScript中使用CSS选择器,以便设计师可以自由更改它们无论他们想要什么而不打破东西,但它也能正常工作。

I generally try to minimize the use of CSS selectors in my JavaScript so that designers are free to change them to whatever they want without breaking things, but it works just as well.

这篇关于如何在Ruby on Rails中为表单元素添加onchange监听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆