[英]How can I get the current index of an element with a class? (JQuery)
這是我的代碼:
$(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”或索引?
試試這個。 這將從同級元素的集合中找到當前索引:
$('.nomeItem').index( $( this ) );
無論如何,請在此處查看DEMO 。 並檢查$('.nomeItem').index( $( this ) );
之間的區別$('.nomeItem').index( $( this ) );
和$( this ).index( );
在行動。
嘗試這樣的事情:(假設您的產品類別為“ clsProduct”
$(document).on("change", ".clsProduct.nomeItem", function() {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.