【问题标题】:Click function by EnrrEnrr 的点击功能
【发布时间】:2017-02-04 11:04:39
【问题描述】:

我有点击功能:

$("#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);
        });
        });

当我尝试添加通过 Enter 键提交输入的功能时,什么也没发生。这个函数带回车提交:

$('#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);
        });
        });
        }
    });

在 HTML 中我有:

<input id="text" type="text" name="message-text" size="63">
<input id="but" type="submit" name="Send" value="Send">

【问题讨论】:

  • 在按键上你没有触发你想要的动作,你正在将事件处理程序附加到#but元素
  • 谢谢队友,我是 jQuery 新手
  • @Hellbea 你可以检查我编辑的答案,它更优化。

标签: javascript jquery django-templates


【解决方案1】:

您正在附加keypress 事件和内部click,所以要解决这个问题;这是一个建议

第一次尝试分解重复的代码,这样如果有任何编辑,你只需要做一次:

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);
            });
    }

所以现在您有一个发送请求的函数,现在您将处理您的函数将被触发的事件,只需键入

$('#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();
        }
    });

你对点击做同样的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    相关资源
    最近更新 更多