如何使用jquery从输入文本数组中检测当前输入文本的索引

时间:2013-06-25 15:45:33

标签: javascript jquery arrays jquery-selectors

我有一个简化的输入文本框数组:

<input type="text" name="quantity[3]" value="0">
<input type="text" name="quantity[6]" value="0">
<input type="text" name="quantity[7]" value="0">
<input type="text" name="quantity[11]" value="0">

这两种方式中的任何一种对我来说都是可以接受的,但我不知道如何做其中一种:

当第3个输入框(有索引7)改变时,我可以接受两个alert()中的任何一个:

  • 7(因为第3个文本框的真实索引是7
  • 2(因为它可能会从0开始计算,因此其索引将为2)

我的代码不起作用是:

$(document).ready(function(){
    $('input[name^=quantity]').change(function(){
        alert($(this).index());
    });
})

链接: http://niamco.com/cp/problem.html

当用户更改任何数量文本框时,系统会提示文本框的val()以及正确的index()。我们看到val()输出正确,但index()始终返回0

由于val()是正确的,我们应该确保jQuery加载良好并且正常工作。那么为什么index()不应该是真的呢?

奇怪的是,正如我研究的那样,val()index()都是jQuery功能。如果val()是javascript基础,则可以接受。但是现在,一个jquery Base函数可以工作,而另一个则没有!

2 个答案:

答案 0 :(得分:7)

.index()获取元素相对于其兄弟姐妹的当前位置。您应该使用正则表达式来获取输入名称中[]之间的数字。

请改用:

$('input[name^=quantity]').change(function () {
    var index = $(this).prop('name').match(/\[(.*?)\]/)[1];
    console.log(index);
});

这里有效:http://jsfiddle.net/u8HRq/1/

更新:根据您的更新,这是一个工作小提琴:http://jsfiddle.net/qbmAU/2/

首先关闭id应该是唯一的,所以我已将它们更改为类并更新了change事件的选择器。

我也有.index()工作:

$(this).index('.quantity')

index()通常通过返回相对于匹配兄弟姐妹的位置来工作,这就是我和j08691的答案正常工作的原因。但是,如果元素不是兄弟元素,那么您可以将选择器作为参数传递。这将返回当前元素相对于匹配元素的index

答案 1 :(得分:2)

这两者都得到了:

 $('input[name^=quantity]').change(function () {
     console.log($(this).index(), +$(this).prop('name').match(/\d+/g));
 });

<强> jsFiddle example

$(this).index()是真正的索引

+$(this).prop('name').match(/\d+/g)是属性

的索引

更新:在您更新问题以显示您真正使用的代码后,这应该可以帮助您:

$('input[name^=quantity]').change(function () {
    console.log($(this).closest('table').find('input[name^=quantity]').index($(this)), +$(this).prop('name').match(/\d+/g));
});

+$(this).prop('name').match(/\d+/g)仍可用于从属性

获取索引

$(this).closest('table').find('input[name^=quantity]').index($(this))但是您需要使用.index()这种格式来获取输入元素的索引,因为它们不是彼此的兄弟姐妹。您需要为要比较它们的元素集合传递参数,在本例中为$(this).closest('table').find('input[name^=quantity]')