我对 Rails 中的 Javascript 和 Jquery 很陌生,所以如果以前有人问过类似的问题,我深表歉意。我一整天都被这个问题困扰了。 我的表单中有三个字段:“从位置”、“到位置”和“数量”。当“来自位置”选择字段更改时,我想要:
- 将“目标位置”更改为删除“起始位置”中选定的字段
- 反射(reflect)“出发地点”可用数量的“数量”。
我将其写入我的项目模型的 edit.js.erb 文件中。
我已为所有字段指定了不同的类,并按类引用特定字段,但 .on change() 正在针对所有选择字段触发。
(变量 fohInventoryItems 是通过该模型索引页中的脚本 block 提供的。) 这是我的代码:
var selectedItemClass = <%=@item.id%>
(document).on('change', $('select.' + selectedItemClass + "." + 'from-select').eq(0), function() {
});
她是我在 _form.html.erb 中针对此模型的代码:
<%= form_for item, remote: true, format: "js" do |f| %>
<%= f.label :from_location %><br>
<%= f.collection_select :location_ids, item.locations.uniq, :id, :name, {selected: item.locations.uniq.first}, { class: "form-control #{item.id} from-select", } %><br>
<%= fields_for :line_items, item.line_items.build do |l| %>
<%= l.label :to_location %><br>
<%= l.collection_select :location, Location.all, :id, :name, {}, { class: "form-control #{item.id} to-select" } %><br>
<%= f.label :quantity %><br>
<%= f.select :quantity, (Array (1..item.quantity)), {}, { class: "form-control #{item.id}" } %>
<%end%>
<br>
<div style="text-align: center;">
<%= f.submit "Move", class: "#{item.id} submit" %><br>
</div>
<% end %>
最佳答案
当使用 on()
作为委托(delegate)事件处理程序时,第二个参数在内部用作过滤器来检查元素是否与选择器匹配。
文档明确指出语法是
.on( events [, selector ] , handler )
选择器
为
selector
Type: StringA selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element.
它是字符串的原因是,将根据它检查元素,因此它不能是另一个 jQuery 集合。
...这意味着您必须将代码更改为
$(document).on('change', '.' + selectedItemClass + 'from-select', function() {...
关于javascript - Jquery .on change() 命中 js.erb 文件中的所有选择字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44837976/