javascript - 按 Enter 键时调用单击函数

标签 javascript php jquery

我一直很难弄清楚为什么按键不起作用。不,我的意思是它可以工作,但返回的结果是 json。我想像按下“发布”按钮时一样返回 html。如何使回车键和按钮单击功能相同?谢谢!这是我到目前为止的代码。

Note: The code works fine after clicking the post comment button but returns a json data if pressing enter key.

JS:

function commentApp(item_id){
  $('.js-post-button').on('keypress click', function(e){
    var url = $('form#js-post-comment').attr('action');
    if (e.which === 13 || e.type === 'click') {
    $.ajax({
      type     : 'POST',
      url      : url,
      dataType : 'json',
      data     : $('#js-post-comment').serialize(),
      success  : function(result) {
        $('#js-input-comment').val('');
        showComments(item_id);
      }
    });
    }
  });
}

function showComments(item_id) {
  var url = $('#js-comment').attr('data-url');
  $.ajax({
    url       : url+'/comments/'+item_id,
    type      : "POST",
    dataType  : "html",
    success   : function(result) {
      $('#js-comment').html(result);
    }
  });
}

PHP:

$data = array(
      'checklist_item_id' => $id,
      'comment'           => $this->input->post('comment'),
      'date_posted'       => date('Y-m-d h:i:s'),
      );

    $this->item_comments->insert($data);
    echo json_encode($data);

HTML:

<form id="js-post-comment" method="post" role="form" action="<?php echo site_url('document_items/add_comment/'.$value['checklist_item_id'])?>">
   <div class="input-group">
    <input id="js-input-comment" type="text" class="form-control" name="comment" placeholder="Write a comment...">
     <span class="input-group-btn">
       <button class="js-post-button btn btn-default" type="button">Comment</button>
     </span>
    </div><!-- /input-group -->
</form>

最佳答案

您应该监听表单上的提交事件:

$('#js-post-comment').on('submit', function(event) {
  event.preventDefault(); // stop form from making native submit

  var url = $(this).attr('action');
  $.ajax({
    type     : 'POST',
    url      : url,
    dataType : 'json',
    data     : $(this).serialize(),
    success  : function(result) {
      console.log('Do something with result:');
      console.log(result);
    }
  });
});

关于javascript - 按 Enter 键时调用单击函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37584031/

相关文章:

php - 使用 phpseclib 从远程服务器下载文件

javascript - 在 Windows 刷新事件中继续使用带有十进制计数器的数字

javascript - Fullcalendar 和 jQuery 日期选择器

javascript - 在 fancybox 中单击按钮时将参数传递给 afterclose 回调

php7.4 mysqli 超时并显示 "gone away"

javascript - 无法在 javascript jQuery 中获取点击事件

javascript - JavaScript : Accessing another method of the same object?

javascript - 仅在 Prop 更改时渲染子组件

javascript - 使用 Javascript 将复杂的 HTML 动态添加到 div

php - 在 php 中创建脚本以在图像上创建亚克力效果