如何在javascript中为html上的动态添加字段匹配id
How to match id in javascript for dynamically added field on html?
在我们的rails应用程序中,可以将动态字段添加到表单中。以下是动态添加字段order_order_items_attributes_1413563163040_unit_price
:的html源代码
<div class="input decimal required order_order_items_unit_price">
<label class="decimal required control-label" for="order_order_items_attributes_1413563163040_unit_price">
<abbr title="required">*</abbr>
Unit Price($)
</label>
<input id="order_order_items_attributes_1413563163040_unit_price" class="numeric decimal required span5 span5" type="number" step="any" name="order[order_items_attributes][1413563163040][unit_price]">
</div>
正如您所看到的,字段的id中有一个13位的字符串,它是在添加字段时随机生成的。我们如何在javascript中匹配(定位)这种类型的随机id?rails应用程序使用jquery(例如$('#order_order_items_attributes_xxxxxxxxxxxxx_unit_price').change(function (){})
)。
我们不熟悉这种css类型的id匹配。请提供更多细节。
您必须首先决定使用什么算法来匹配id值。根据您的评论(在您的问题中没有精确指定),您似乎想找到所有以"order_order_items_attributes_"
开头、以"_unit_price"
结尾的ID,并且它们之间有一系列数字。
你可以这样做,找到所有以你想要的东西开始的id,然后将它们过滤到只符合所有三个标准的东西:
// find ids that match this pattern: order_order_items_attributes_xxxxxxxxxxxxx_unit_price
var orderItemRegex = /^order_supplier_id_'d+_unit_price$/;
$("[id^='order_supplier_id_']").filter(function(index) {
return orderItemRegex.test(this.id);
}).change(function() {
// this will be only the ids that match
});
这使用jQuery来列出id以"order_supplier_id_"
开头的所有对象。然后,它在该列表中进行筛选,消除与定义模式的完整正则表达式/^order_supplier_id_'d+_unit_price$/
不匹配的任何对象,然后将.change()
事件处理程序仅连接到通过正则表达式测试的对象。
你试过吗
$("input").prop("id");
这将搜索您的输入字段并找到id属性。
使用<label>
:的for
属性
var selector = $('.decimal.required.control-label').eq(0).attr('for'),
element = $('#'+selector);
console.log(element);
// [<input id="order_order_items_attributes_1413563163040_unit_price" ... >]
您可以使用属性选择器来匹配"包含"指定值的id,使用[attr*=value]
。类似:
$("[id*='order_supplier_id']").change(function() {
});
MDN关于属性选择器的文档指定了可以用于匹配属性的选择器的类型,其中包括:
[attr*=value]
表示属性名称为attr的元素,其值至少包含一个字符串"value"作为子字符串。
您可以维护一个元素ID数组,该数组在每次添加表单元素时都会更新。然后对数组中的元素调用change方法。但是,如果更改事件回调对于所有新元素都是相同的,那么这就没有必要了。只要把它记在课堂上就行了。
- 正在添加动态第二类Jquery
- 如何在javascript而不是jquery中添加动态列表
- 为图例添加动态色彩标签
- 如何在谷歌表单中添加动态字段
- 如何添加动态Id's并在运行时提取它们
- 在 JavaScript 中添加动态文本
- 如何添加动态表单元素但保留其值(JS)
- 使用AngularJs在自定义TinyMCE编辑器中添加动态数据
- 如何使用JavaScript添加动态HTML内容(DIV)
- javascript初学者:在javascript中添加动态样式
- 如何使用Javascript在html源中添加动态数据
- 向Uploadify添加动态字段
- 如何在 Vue.js 中添加动态组件/部件
- 锚导航与坚持到顶部菜单..需要向锚点添加动态偏移量
- Javascript:添加动态方法
- 向角度对象添加动态功能
- 添加动态文本框时更新动态高度
- JavaScript 运行时错误:无法在 Windows 8 应用中添加动态内容
- 添加动态点击事件
- 添加动态字段以创建特定的 JSON 格式