我试图从表单输入中抓取动态生成的ID,然后等待用户提交它并仅在ID包含字符串"comment"时处理提交。目前,我可以获得ID,但提交默认操作没有被阻止,并且发生常规POST操作而不是ajax。几天来,我一直试图自己解决这个问题,但我感到很失败……如有任何帮助,我将不胜感激。
$(document).ready(function() {
var fullID;
$(".post-new-comment-input").click(function(){
fullID = $(this).attr('id');
});
$(this).submit(function(e)
{
if(fullID.indexOf("comment") > -1) <?php // execute only if the fullID contains "comment" ?>
{
e.preventDefault();
var value = $('#'+fullID).val();
var justID = fullID.substring(8); <?php // truncate first 8 chars, the 'comment-') ?>
$.ajax({
type: "POST",
url: "actions",
data: { 'comment-pid': justID, 'comment-uid': <?php echo get_current_user_id(); ?>, comment: value },
dataType: 'json',
success : function(response)
{
$('#post-discussion-'+justID).html(response[0]);
$('#comments-count-'+justID).html(response[1]);
}
});
$('#'+fullID).val(null); <?php // clear the input field after returning post result ?>
}
});
});
表格如下:
<div class="comment-form">
<form>
<input type="text" id="comment-<?php echo $post_id; ?>" class="post-new-comment-input" placeholder="Write your comment...">
<input type="submit" class="hide">
</form>
</div>
(对不起,如果格式混乱,我不习惯如何SO的帖子格式)
我不太明白你在做什么。从代码的设置方式来看,似乎是在用户单击注释字段时触发提交注释。我认为这不是期望的行为,您更可能希望在用户按下评论文本区域字段中的enter键时触发提交(就像在Facebook上一样),在这种情况下,您可能希望使用"keyup"事件处理程序。然后,submit函数将检查是否按下了enter键,否则不执行任何操作。
$(".post-new-comment-input").on("keyup", function (event) {
if (e.keyCode == 13) {
[YOUR AJAX POST CODE HERE]
} else return false;
});
话虽如此,我不确定用户看到一个没有提交按钮的表单有多直观(对于非技术悟性…)如果您确实想要包含Submit按钮并让它以任何一种方式工作,您可以将代码放入单独的提交事件处理程序中,然后在用户按下文本区域中的enter键时触发提交事件。
如果我是你,我会把这个事件附加到form元素的submit事件上。
为了防止默认事件,你应该从函数返回false。或者你可以使用event.preventDefault()。
但是在on-submit事件中这样做是正确的。我认为!:)