简体   繁体   English

Ruby on Rails渲染部分无法从主窗体视图执行javascript

[英]Ruby on rails render partial does not execute javascript from the main form view

I'm trying to execute JavaScript from the main view form, from the rendered partial when I click on the checkbox in the rendered partial but that JavaScript doesn't execute. 我尝试从主视图表单,从渲染的部分执行JavaScript,方法是单击渲染的部分中的复选框,但该JavaScript无法执行。 It only execute if I copy the content of the partial in the main view. 仅当我在主视图中复制部分内容时,它才会执行。 I've searched the site, but I can't get an answer. 我已经搜索了该站点,但是找不到答案。 This is what I have, for example: 这就是我所拥有的,例如:

app/views/people/_main_form.html.erb app / views / people / _main_form.html.erb

<script>
  view something in partal
  $('people_visible_by_default').click(function(){
    alert("Can you see me");
  });
</script>

<%= bootstrap_nested_form_for @people, html: { class: 'form-horizontal', id: 'people_edit_form' } do |f| %>
   <%=  render partial: 'form_partial', locals: { f: f } %>
<% end %>

The checkbox to be executed in the app/views/people/_form_partial.html.erb 要在app / views / people / _form_partial.html.erb中执行的复选框

<%= f.check_box :visible_by_default, data: { preview_type: 'none' } %>

clicking on the visible_by_default checkbox doesn't show the alert as I expected.  How do I get it to execute when it is in the main_form.html.erb

I guess you are using id of the checkbox("people_visible_by_default") as the selector in jQuery. 我猜您正在使用复选框的ID(“ people_visible_by_default”)作为jQuery中的选择器。 But you forgot to append "#" before it. 但是您忘了在其前面附加“#”。

So, try with 因此,尝试

$('#people_visible_by_default').click(function(){
  //your code
});

OR 要么

$('#your_form_ID').on('click', '#people_visible_by_default', function(){
  //your code
});

First of all, you should use the selector you have when loading the main page. 首先,加载主页时应使用选择器。 Js iterates dom elements when loading main page. 加载主页时,Js会迭代dom元素。 So if you rendering something by event (something unexisting in beginning of page loading), there is no js handler. 因此,如果您通过事件渲染某些东西(页面加载开始时不存在的东西),则没有js处理程序。 But you can use selector of parent element of rendered partial. 但是您可以使用呈现部分的父元素的选择器。 For example: 例如:

view.html.slim : view.html.slim

.parent_class
  = bootstrap_nested_form_for @people, html: { class: 'form-horizontal', id: 'people_edit_form' } do |f| 
   =  render partial: 'form_partial', locals: { f: f } 

view.js.coffee view.js.coffee

$('.parent_class').on 'click', '#people_visible_by_default', (e) ->
  do something 

Try this. 尝试这个。 I hope it'll help you 希望对您有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM