如何获取数组文本框中文本框的键(索引)值

How to get key (index) value of a textbox in array textboxes

本文关键字:文本 索引 中文 数组 何获取 获取      更新时间:2023-09-26

我想要一个jQuery函数或javascript提醒索引和数组文本框的值:例如

<input type="text" name="textbox[]" value="1" onblur="javascriptfunction(this.value,this.index)" />
<input type="text" name="textbox[]" value="foo" onblur="javascriptfunction(this.value,this.index)" />
<input type="text" name="textbox[]" value="banana" onblur="javascriptfunction(this.value,this.index)" />

每当鼠标从第一个输入移动时,我就提醒(1,0),第二次是(foo,1)等等。我找不到这样的函数。请帮助。

您可以使用jQuery index()和val()像

$('input').blur(function(){
  alert($(this).val() + ',' + ($(this).index()-1));
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input type="text" name="textbox[]" value="1" />
<input type="text" name="textbox[]" value="foo" />
<input type="text" name="textbox[]" value="banana" />

要针对某些元素或在命名函数中使用这些元素,首先,在元素上放置标识符,例如类my-class。然后,创建一个命名函数并将其传递给jQuery模糊函数

$('.my-class').blur( alertIndexAndVal );
function alertIndexAndVal(){
  alert($(this).val() + ',' + ($(this).index()-1));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input class="my-class" type="text" name="textbox[]" value="1" />
<input class="my-class" type="text" name="textbox[]" value="foo" />
<input class="my-class" type="text" name="textbox[]" value="banana" />

var textboxes = $('input[name="textbox[]"]');
textboxes.on('blur', function() {
    var index = textboxes.index( this );
    alert( this.value + ', ' + index );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="textbox[]" value="1"  />
<input type="text" name="textbox[]" value="foo"  />
<input type="text" name="textbox[]" value="banana"  />

我想我会发布一个javascript解决方案,这是诚实的尝试做一些像jquery的索引函数,虽然我认为jquery函数可能更好。

var getIndexValue = function (e) {
    var children = e.parentElement.children;
    for (var i = 0; i < children.length; i++) {
        if (children[i] == e) {
            alert("Index: " + (i+1) + ", Value: " + e.value);
        }
    }
}
<div>
    <input type="text" name="textbox[]" value="one" onblur="getIndexValue(this)">
    <input type="text" name="textbox[]" value="two" onblur="getIndexValue(this)">
    <input type="text" name="textbox[]" value="three" onblur="getIndexValue(this)">
</div>

指数:(i + 1)

值:(e.value);