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 に答える