1

我有一个包含多个文本输入的页面,我想确定用户正在输入哪些文本输入。所有文本输入都使用相同的代码显示。一个很大的限制是我不能修改实际的 HTML 代码,所以我不能在输入中添加 ID 或类。

这是 HTML 的样子:

<input type="text" />
<input type="text" />
<input type="text" />
<input type="text" />

这是我用来检测按键的代码:

$(document).keypress(function(e) {
console.log(e.target) // will be the same for each input
});

有没有办法区分不同的输入。是否有一个底层 DOM 属性可以区分文本输入,以便我可以在将来的恒定时间内访问输入(即,DOM 是否为每个输入分配一个唯一的 id)?

4

2 回答 2

1

在文档加载时,您可以遍历输入元素并制作“索引”=>“元素”映射。这可用于将来的恒定时间访问。地图的索引可以作为元素的唯一 ID。

我为此准备了一个工作小提琴。http://jsfiddle.net/fugHv/6/。这能解决你的问题吗?

这是该方法的要点,

$(document).ready(function(){
    var inputMap = {}, inputArray = [];

    $.each($('input'), function(i, v){
        //Make an array of the inputs to ensure a constant time access
        inputArray.push(v);
        //Make a map of inputs with index as the key, for future use
        inputMap[i] = v; 
    });

    $('input').keypress(function(e){
        var pos = inputArray.indexOf(e.target);

        //This should provide the reference for the target input
        var inputRef = $(inputMap[pos]);
        ...
    }); 
});
于 2013-07-12T07:19:41.133 回答
1

您可以使用 jQuery 索引方法唯一标识输入:

$(document).keypress(function(e) {
console.log(e.target) // will be the same for each input
console.log($(e.target).index());
}); 
于 2013-07-12T09:11:54.890 回答