gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 14:34:13 25 4
gpt4 key购买 nike

我一直很难弄清楚为什么按键不起作用。不,我的意思是它可以工作,但返回的结果是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com