这是我的代码:
$(document).on("change", ".nomeItem", function() {
if ($(this).val().length) {
$(this).addClass("input-green");
$(this).removeClass("input-red");
$(this).removeClass("input-white");
if (!($(this).index() in itemNames)) {
itemNames.add($(this).index());
itemNames.activate($(this).index());
} else {
itemNames.activate($(this).index());
}
} else {
$(this).addClass("input-red");
$(this).removeClass("input-green");
$(this).removeClass("input-white");
showGeneralMessage("É necessário preencher a quantidade!", "danger");
itemNames.deactivate($(this).index());
}
console.log("Nome: " + JSON.stringify(itemNames));
});
在页面上,有一个添加新“产品”的按钮,这个“产品”里面有这个类(“.nomeItem”)。 $(this).index()
应该给我当前索引(例如,如果我在第三个产品中触发更改事件)。然而,它总是返回1.如何获得具有类的元素的当前“eq”或索引?
答案 0 :(得分:1)
试试这个。这将从兄弟元素集合中找到当前索引:
$('.nomeItem').index( $( this ) );
无论如何,请在此处查看DEMO。并检查$('.nomeItem').index( $( this ) );
和$( this ).index( );
之间的差异。
答案 1 :(得分:0)
尝试这样的事情:(假设你的产品类是" clsProduct"
$(document).on("change", ".clsProduct.nomeItem", function() {