gpt4 book ai didi

javascript - 如何编写一个简洁的 JS if else 语句来通过 Cocoon 动态添加嵌套的 Rails simple_form?

转载 作者:行者123 更新时间:2023-12-03 04:00:56 25 4
gpt4 key购买 nike

我正在使用 cocoon 在 Rails 中构建嵌套的 simple_form_for 来动态添加和删除嵌套元素。主要模型对象是报价单,并且报价单有许多员工。我已经达到了业余代码技能的极限,希望获得一些关于编写简洁的 js 脚本的指导,以实现以下目标:

  • 如果nested_object.count <= 2,则remove_empee_link.hide
  • 如果nested_object.count > 2,则remove_empee_link.show,但不在前两个nested_objects上。

  • 如果nested_object.count > 10,则add_empee_link.hide,否则始终add_empee_link.show

改编自一篇非常有用的帖子here感谢 @nathanvda 我已经到了这里;

$(document).ready(function() {
function check_to_hide_or_show_add_empee_link() {
if ($('#empee-form .nested-fields:visible').length == 5) {
$('#empee-form .links a').hide();
} else {
$('#empee-form .links a').show();
}
}

$('#empee-form').on('cocoon:after-insert', function() {
check_to_hide_or_show_add_empee_link();
});

$('#empee-form').on('cocoon:after-remove', function() {
check_to_hide_or_show_add_empee_link();
});

check_to_hide_or_show_add_empee_link();
});

$(document).ready(function() {
function check_to_hide_or_show_remove_empee_link() {
if ($('#empee-form .nested-fields:visible').length <= 2) {
$('.remove_fields').hide();
} else {
$('.remove_fields').show();
}
}

$('#empee-form').on('cocoon:after-insert', function() {
check_to_hide_or_show_remove_empee_link();
});

$('#empee-form').on('cocoon:after-remove', function() {
check_to_hide_or_show_add_remove_empee_link();
});

check_to_hide_or_show_add_remove_empee_link();
});

但是我正在努力制定一个策略,说明如何以一个简洁的解决方案实现我在上面的 biullets 中概述的目标,在开始并玩了几个小时后,任何指导都会非常感激。谢谢

我现在编写的更新代码,但行为是意外的;

  • 如果页面上有 1、2 或 3 个嵌套元素,则所有删除链接都会隐藏。
  • 如果页面上有 4 个嵌套元素,则第 1 个、第 2 个和第 4 个元素将隐藏 remove_link
  • 如果页面上有 5 个嵌套元素,则第 1 个、第 2 个和第 3 个元素将隐藏 remove_link

预期的行为,第一个和第二个删除链接始终隐藏,其他显示:

// Hiding the 1st 'remove employee' link for the first two employee fields.
$(document).ready(function() {
function hide_first_and_second_remove_empee_links() {
var remove_links = $('.remove_fields')
$(remove_links[0]).hide();
$(remove_links[1]).hide();
// $('a.remove_fields:first-child').hide();
// $('a.remove_fields:nth-child(2)').hide();
}
$('#empee-form').on('cocoon:after-insert', function() {
hide_first_and_second_remove_empee_links();
});
$('#empee-form').on('cocoon:before-insert', function() {
hide_first_and_second_remove_empee_links();
});
hide_first_and_second_remove_empee_links();
});

怎么会这样呢?有一种方法,它将所有 .remove_fields' 收集到remove_links var中,然后将该集合的[0]元素包装在 jQuery 对象中并调用hideon它。然后同样到 1 元素。该方法在页面就绪时调用,然后在 cocoon:before-insertafter-insert 上调用。我不明白[0]1的定义如何` 元素发生变化?

最佳答案

当你写下你的逻辑会变得更容易:

  • 始终隐藏前两个删除链接
  • 如果员工超过 10 人,则隐藏添加关联链接

第二个已经在您的答案中涵盖了。

第一个实际上使用 jquery 非常简单:

$('.remove-fields:first-child').hide()
$('.remove-fields:nth-child(2)').hide()

关于javascript - 如何编写一个简洁的 JS if else 语句来通过 Cocoon 动态添加嵌套的 Rails simple_form?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44727012/

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