如何使用jQuery定位name属性含动态ID的表单元素?
解决方案
针对这类name属性包含随机ID的元素,你可以通过以下几种方式构建动态选择器来绑定change事件:
1. 精准匹配name属性的首尾规则
利用jQuery的属性前缀(^=)和后缀($=)选择器,匹配name以customer[customer_food_attributes][开头、以][customer_id]结尾的select元素:
$('select[name^="customer[customer_food_attributes]["][name$="][customer_id]"]').on('change', function(e) { // 这里编写你的事件逻辑 console.log('当前选中值:', $(this).val()); console.log('当前元素的name属性:', $(this).attr('name')); });
2. 模糊匹配name属性的特征片段
如果不需要特别精准,也可以用属性包含(*=)选择器,匹配name中同时包含customer[customer_food_attributes]和[customer_id]的select元素:
$('select[name*="customer[customer_food_attributes]"][name*="[customer_id]"]').on('change', function(e) { // 事件逻辑代码 });
3. 利用元素的共同类名(更简洁)
观察你的元素,它们都带有form__select、form__input这类共同类名,直接通过类选择器绑定,若担心误绑定其他同类型元素,可额外判断name属性:
$('.form__select').on('change', function(e) { const elemName = $(this).attr('name'); // 验证name是否符合目标规则 if (elemName?.startsWith('customer[customer_food_attributes][') && elemName.endsWith('][customer_id]')) { // 执行你的业务逻辑 } });
4. 事件委托(应对动态生成的元素)
如果这些select元素是后续动态添加到页面中的,必须使用事件委托,将事件绑定到它们的父容器(比如form或更上层的静态容器):
// 假设父容器是form,替换成你实际的父选择器 $('form').on('change', 'select[name^="customer[customer_food_attributes]["][name$="][customer_id]"]', function(e) { // 事件逻辑代码 });
内容的提问来源于stack exchange,提问作者Samuel D.
相关产品推荐
相关产品推荐

