gpt4 book ai didi

javascript - 在rails中使用远程以ajax渲染形式执行脚本

转载 作者:行者123 更新时间:2023-11-28 06:26:23 26 4
gpt4 key购买 nike

按下此按钮后我呈现表单

= link_to 'New Note', new_note_path, :class => "btn btn-primary new-note-button", :type => "button", :id => "new-link", remote: true

通过new.js.erb中的这个脚本

$("#new-link").hide().after('<%= j render("form") %>');

它渲染的表单可以工作,但是 application.js 中控制该表单的脚本却不能。顺便说一句,如果表单是从页面加载生成的,而不是使用 js 生成的,它就可以工作。
其中有一个

  $("#noteContent")
.on("input", function(){
checkExistNoteContent();
})
.ready(function(){
checkExistNoteContent();
});

请帮帮我,如何解决这个问题?

rails 4.2.5

DOM

 .container.main-section-index
%h1.text-center Notes
-if user_signed_in?
= link_to 'New Note', new_note_path, :class => "btn btn-primary new-note-button", :type => "button", :id => "new-link", remote: true
-else
= link_to 'Sign up!', new_user_registration_path, :class => "btn btn-primary sign-up-index", :type => "button"
= link_to 'Log in!', new_user_session_path, :class => "btn btn-primary log-in-index", :type => "button"
%hr.head-devide
//other elements

此处表格的简短版本:

= form_for(@note) do |f|
.field
%h5.label-of-content Content
%br/
= f.text_area :content, {:class => "form-control content-input", :id => "noteContent"}
%br/
.actions
= f.submit "#{button_label}", {:class => "btn btn-default", :id => "submitNote", :disabled => "disabled"}

最佳答案

您需要委托(delegate)您的 .on 函数:

#app/assets/javascripts/application.js
$(document).on("input", "#noteContent", function(){
checkExistNoteContent();
}).ready(function(){
checkExistNoteContent();
});

每当您将 JavaScript 函数“绑定(bind)”到元素上的事件时,元素会在 DOM 加载时出现。

如果加载时该元素不存在,JQuery 使您能够将事件绑定(bind)到另一个元素,并将函数委托(delegate)给子元素(可以稍后加载)。

--

来自docs :

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

关于javascript - 在rails中使用远程以ajax渲染形式执行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35092677/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com