1

我有几个使用相同 ID 和相同名称动态创建的文本输入。每当用户在该文本输入中按下“Enter”键时,我都想获取在特定文本输入中键入的数据。

例如,我有

<input type="text" id="fetchChatMsg" name="chat" />
<input type="text" id="fetchChatMsg" name="chat" />
<input type="text" id="fetchChatMsg" name="chat" />
<input type="text" id="fetchChatMsg" name="chat" />

每个输入都是在某个事件上动态创建的。现在假设屏幕上有 4 个文本输入。用户可以在其中输入任何内容。我希望每当用户在任何文本输入中按下“Enter”键时,都应该提醒该特定文本输入中的数据。

我用过:

$(document).on('keypress','#fetchChatMsg', function(e) {
    if(e.which==13)
        alert($('#fetchChatMsg').val());
});

但这真的很模棱两可。请解决这个问题,也许类可以处理这个?

4

1 回答 1

0

试试这个,而不是重复的 ID,而是类。

jQuery

$(document).on('keypress','.fetchChatMsg', function(e) {
    if(e.which==13)
        alert(this.value);
});

HTML

<input type="text" class="fetchChatMsg" name="chat" />
<input type="text" class="fetchChatMsg" name="chat" />
<input type="text" class="fetchChatMsg" name="chat" />
<input type="text" class="fetchChatMsg" name="chat" />

演示在这里

于 2013-10-15T20:12:08.530 回答