jQuery监听Symfony集合表单change事件时如何获取触发元素的对应ID
实现方案
你当前的事件绑定逻辑完全可以复用,不需要推翻重写,核心是利用jQuery事件回调自带的上下文拿取当前触发事件的元素信息。
- 事件回调中,
this指向的就是实际触发change事件的原生DOM节点,不需要额外追踪是哪个元素触发的,直接从这个节点的ID值中提取对应的集合索引即可。 - 你现有的ID结构是固定格式:
user_working_hours_weeks_{数字}_regularity,可以直接用正则提取中间的数字部分,作为索引传给你封装好的显示/隐藏函数。
调整后的绑定代码如下,完全保留你原来的数组拼接选择器的逻辑:
var regularityWeeksArray = [ '#user_working_hours_weeks_0_regularity', '#user_working_hours_weeks_1_regularity', '#user_working_hours_weeks_2_regularity', '#user_working_hours_weeks_3_regularity' ] var regularityWeeksArrayToString = regularityWeeksArray.join(', '); $(document).on('change', regularityWeeksArrayToString, function() { // 匹配当前元素ID中的集合序号 const idMatch = this.id.match(/user_working_hours_weeks_(\d+)_regularity/); // 匹配失败时直接跳出,避免脚本报错 if (!idMatch) return; const currentIndex = idMatch[1]; if($(this).val() === 'interim'){ showInterimWithID(currentIndex); } else { hideInterimWithID(currentIndex); } });
动态集合项的适配优化
目前你写死的ID数组仅覆盖前4个集合项,使用Symfony Collection Bundle动态新增的集合项(比如第5、6...个输入框,对应的ID为user_working_hours_weeks_4_regularity这类结构)无法被现有选择器匹配,会导致新生成的元素没有对应交互逻辑。
不需要手动维护ID数组,可以直接将选择器替换为通配匹配同结构元素的表达式,一次匹配所有符合规则的输入框:
// 匹配所有符合ID结构的regularity输入框,不管是已存在的还是动态新增的 const regularitySelector = '[id^="user_working_hours_weeks_"][id$="_regularity"]'; $(document).on('change', regularitySelector, function() { // 索引提取、交互判断的逻辑和上面完全一致,不需要改动 const idMatch = this.id.match(/user_working_hours_weeks_(\d+)_regularity/); if (!idMatch) return; const currentIndex = idMatch[1]; if($(this).val() === 'interim'){ showInterimWithID(currentIndex); } else { hideInterimWithID(currentIndex); } });
这种写法完全兼容你现有的showInterimWithID、hideInterimWithID函数,不需要改动函数本身的ID拼接逻辑。
内容的提问来源于stack exchange,提问作者Jakub Novák
相关产品推荐
相关产品推荐

