2013-06-01 32 views
0

我想写点聊天。 在页面的第一次加载时,旧的消息和答案将从数据库中加载。所以我有很多不同ID的消息。对于每条消息,我都有一个链接来回复。当你点击它时会出现一个消息框。我的问题是,我想在用户按下键盘上的Enter键时发送回复。许多动态添加的textareas的jQuery keypress事件

回复文字区域与jQuery的加入,所以我不能用$(文本域).keypress(.....)

这里是我的代码示例:

<div id="container" style=""> 
<div id="main" role="main"> 
    <div id="shoutbox_container"> 
     <div id="shoutbox_content" style="margin-top:20px;"></div> 
    </div> 
</div> 

for (id = 0; id < 5; id++) { 
    var res_container = '<div id="shoutbox_entry_' + id + '" class="entry entrybox">'; 
    res_container += 'Mr Idontknow wrote:' + id + '. Message '; 
    res_container += ' <span class="reply" id="reply" data-parentid="' + id + '">reply</span> '; 
    res_container += '<div class="replytextbox replybox" id="reply_textbox_' + id + '" style="display:none;">'; 
    res_container += '<textarea class="replytext" name="antwort" id="antwort_' + id + '" data-parentid="' + id + '"></textarea>'; 
    res_container += '<button id="replysend">send</button> '; 
    res_container += '</div>'; 
    res_container += '</div><br><br>'; 
    $('#shoutbox_content').prepend(res_container); } 

//reply textarea 
$('#shoutbox_content').on('click', '#reply', function() { 
    var parentid = $(this).data('parentid'); 
    $('#shoutbox_content').find('#reply_textbox_' + parentid).toggle(); 
}); 

//reply send button 
$('#shoutbox_content').on('click', 'button', function() { 
    var parentid = $(this).prev('textarea').data('parentid'); 
    var reply = $(this).prev('textarea').val(); 
    $(this).prev('textarea').val(''); 
    $('#shoutbox_content').find('#reply_textbox_' + parentid).hide(); 

    if (reply.length > 0) { 
     alert('save reply ' + parentid); 
    } 
}); 

// when the client hits ENTER on their keyboard 
$('#shoutbox_content').keypress('textarea', function (e) { 
    if (e.which == 13) { 
     console.log($(this).find('textarea')); 
     var test = $(this).attr('data-parentid'); 
     alert('Enter ' + test); 
     $(this).blur(); 
     $(this).next('#replysend').focus().click(); 
    } 
}); 

它的工作原理,但我不知道哪个ID被发送。有没有人有一个想法如何我可以找出在哪个答复textarea用户按Enter键?

回答

3

所以,使用。对()与其他人一样的事件声明功能使用的是:

// when the client hits ENTER on their keyboard 
$('#shoutbox_content').on('keypress','textarea', function (e) { 

    //Retrieve ID of the textarea 
    var id = $(this).attr('id'); 

    //Do what you want with id variable 

    if (e.which == 13) { 
     console.log($(this).find('textarea')); 
     var test = $(this).attr('data-parentid'); 
     alert('Enter ' + test); 
     $(this).blur(); 
     $(this).next('#replysend').focus().click(); 
    } 
}); 

然后检索,其中通过检查其身份证或其他属性类似这样的事件发生的textarea的:$(this).attr('id')

+1

谢谢你,它的作品。我想的太复杂了 – Melanie