... "> -6ren">
gpt4 book ai didi

javascript - Dynamic Jquery Function with Rails - 将多个函数压缩为一个

转载 作者:行者123 更新时间:2023-12-03 09:39:16 27 4
gpt4 key购买 nike

现在,我循环遍历 RoR 对象并为每个单独的对象创建一个新的 jquery 函数。我知道这是极其低效且业余的,我希望只有一个 jquery 函数来处理此操作。

<% @startups.each do |startup| %>
<div class="panel-body showVideo<%=startup.id%>">
...
</div>
<div class="panel-body theVideo<%=startup.id%>">
...
</div>
<script type="text/javascript">
$(function () {
$('.theVideo<%=startup.id%>').hide();
$('.showVideo<%=startup.id%>').on('click', function () {
$('.theVideo<%=startup.id%>').show();
$('.showVideo<%=startup.id%>').hide();
});
});
</script>
<% end %>

基本上,此代码等待用户单击该 div,并隐藏该 div,同时显示另一个 div。该代码目前可以工作,但我不想创建大量的函数(当它可能是一个时)!

最佳答案

我认为你只需要让 JS 访问你的 ID 即可。您可以通过将它们写入 HTML 来实现这一点,如下所示:

<script type="text/javascript">
// Write the IDs into the script tag
var ids = [ <% @startups.each do |startup| %>
<%=startup.id%>,
<% end %>];
// Loop over the IDs
for (var i=0; i<ids.length; i++) {
var id = ids[i];
// Do your stuff here
}
</script>

当然添加一些逻辑以确保不要在最后一个添加逗号。

关于javascript - Dynamic Jquery Function with Rails - 将多个函数压缩为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31235107/

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