可能是一些非常愚蠢的东西,但假设我有两个匹配$('[id $ = _ product_id]'的元素)为什么更改事件不能正确匹配?
var numberPattern = /\d+/g;
$('[id$=_product_id]').each(function(idx, elem) {
recordId = elem.id.match(numberPattern)
productId = elem.value;
console.log(recordId);
$("#client_order_order_lines_attributes_" + recordId + "_product_id").on("change", function(e) {
console.log(recordId);
})
});
我创建了一个演示此http://jsfiddle.net/hLYpE/1/
的小提琴我错过了什么?
答案 0 :(得分:2)
你需要来声明这些变量,这是隐式全局变量的危险。
var recordId = elem.id.match(numberPattern);
var productId = elem.value;
答案 1 :(得分:2)
您应该更改在变量名称前添加var的代码:
var numberPattern = /\d+/g;
$('[id$=_product_id]').each(function(idx, elem) {
var recordId = elem.id.match(numberPattern),
productId = elem.value;
console.log(recordId);
$("#client_order_order_lines_attributes_" + recordId + "_product_id").on("change", function(e) {
console.log(recordId);
})
});