gpt4 book ai didi

javascript - rails : hide/close a rendered partial through a button in that partial

转载 作者:行者123 更新时间:2023-12-03 02:41:44 28 4
gpt4 key购买 nike

在我的应用程序中,用户通过 AJAX 呈现 _show.html.erb 部分。我现在想要的是在该部分中有一个按钮,单击时将其关闭。

我遇到的问题:如果我将按钮放在部分之外,一切都会正常 - 我可以 .hide() 部分。但是,该按钮始终可见(这是我不想要的)。一旦我将按钮放入渲染的部分中,关闭部分就不再起作用。

这是为什么呢?我能做什么?

index.html.erb

<div id="show"></div>

show.js.erb

$('#show').html("<%= escape_javascript (render partial: 'recipes/show') %>");

按钮

<div class="btn" id="close-show">Close</div>

JS

$( document ).ready(function() {
$("#close-show").click(function(){
$("#show").hide();
});
});

最佳答案

由于您将代码注入(inject)到 dom,因此 jQuery 事件处理程序不会绑定(bind)到新元素。要使其正常工作,您必须使用 $(document).on 而不是直接监听元素上的事件。
因此将js更改为

 $( document ).ready(function() {
$(document).on("click", "#close-show", function(){
$("#show").hide();
});
});

就可以了。希望这会有所帮助。

关于javascript - rails : hide/close a rendered partial through a button in that partial,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48301758/

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