[英]How can I get the current index of an element with a class? (JQuery)
Here's my code: 这是我的代码:
$(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));
});
On the page, there's a button that adds a new "product", and this "product" has this class inside of it (".nomeItem"). 在页面上,有一个添加新“产品”的按钮,该“产品”中包含此类(“ .nomeItem”)。
$(this).index()
was supposed to give me the current index (For example, if I trigger a change event inside the third product). $(this).index()
应该给我当前的索引(例如,如果我在第三个产品中触发了更改事件)。 Nevertheless, it always returns 1. How can I get the current "eq" or index of an element with a class? 但是,它始终返回1。如何获得带有类的元素的当前“ eq”或索引?
Try use this. 试试这个。 This will find the current index from collection of siblings elements:
这将从同级元素的集合中找到当前索引:
$('.nomeItem').index( $( this ) );
Anyway see DEMO here. 无论如何,请在此处查看DEMO 。 And check the differences between
$('.nomeItem').index( $( this ) );
并检查
$('.nomeItem').index( $( this ) );
之间的区别$('.nomeItem').index( $( this ) );
and $( this ).index( );
和
$( this ).index( );
in action. 在行动。
尝试这样的事情:(假设您的产品类别为“ clsProduct”
$(document).on("change", ".clsProduct.nomeItem", function() {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.