Javascript Enrr的点击功能
我有点击功能:Javascript Enrr的点击功能,javascript,jquery,django-templates,Javascript,Jquery,Django Templates,我有点击功能: $("#but").on('click', function(){ $.post('/chat/send/', { id: $(this).attr("name"), text: $('#text').val(), chat_id: $(".message-box").attr("chat-id"), }, function(response) { var options = '';
$("#but").on('click', function(){
$.post('/chat/send/', {
id: $(this).attr("name"), text: $('#text').val(), chat_id: $(".message-box").attr("chat-id"),
}, function(response) {
var options = '';
$.each(response.data, function() {
options += '<p><b>' + this[0] + ':</b> ' + this[1] + '</p>';
});
$('#text').val('');
$('.message-box').html(options);
});
});
$(“#but”)。在('click',function()上{
$.post(“/chat/send/”{
id:$(this.attr(“name”)、text:$(“#text”).val()、chat_id:$(“.message box”).attr(“chat id”),
},功能(回应){
var选项=“”;
$.each(response.data,function(){
选项+=''+此[0]+':'+此[1]+'';
});
$('#text').val('');
$('.messagebox').html(选项);
});
});
当我尝试添加通过Enter键提交输入的功能时,什么也没发生。使用Enter submit可执行此功能:
$('#text').keypress(function(e){
if(e.which == 13){
$("#but").on('click', function(){
$.post('/chat/send/', {
id: $(this).attr("name"), text: $('#text').val(), chat_id: $(".message-box").attr("chat-id"),
}, function(response) {
var options = '';
$.each(response.data, function() {
options += '<p><b>' + this[0] + ':</b> ' + this[1] + '</p>';
});
$('#text').val('');
$('.message-box').html(options);
});
});
}
});
$('#text')。按键(功能(e){
如果(e.which==13){
$(“#但是”)。在('click',function()上{
$.post(“/chat/send/”{
id:$(this.attr(“name”)、text:$(“#text”).val()、chat_id:$(“.message box”).attr(“chat id”),
},功能(回应){
var选项=“”;
$.each(response.data,function(){
选项+=''+此[0]+':'+此[1]+'';
});
$('#text').val('');
$('.messagebox').html(选项);
});
});
}
});
在HTML中,我有:
<input id="text" type="text" name="message-text" size="63">
<input id="but" type="submit" name="Send" value="Send">
您正在将
按键
事件与单击
连接在一起,以便解决此问题;这里有一个建议
1st尝试对重复的代码进行分解,这样,如果有任何编辑,您只需执行一次:
function sendReq(data){
$.post('/chat/send/', data, function(response) {
var options = '';
$.each(response.data, function() {
options += '<p><b>' + this[0] + ':</b> ' + this[1] + '</p>';
});
$('#text').val('');
$('.message-box').html(options);
});
}
您对单击执行相同的操作。在按键时,您并没有启动所需的操作,而是将事件处理程序附加到#but elementThx mate,我是新来的jQuery@Hellbea你可以查看我编辑过的答案,它更理想。
$('#text').keypress(function(e){
if(e.keyCode == 13){
var data = {id: $(this).attr("name"), text: $('#text').val(), chat_id: $(".message-box").attr("chat-id")}
sendReq();
}
});