2013-06-01 27 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