Jquery:如何将单击侦听器与提交事件函数组合在一起?

时间:2014-05-29 15:04:54

标签: javascript php jquery

我试图从表单输入中获取动态生成的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格式的格式化)

2 个答案:

答案 0 :(得分:2)

我不确定我是否按照你在这里做的事情。您的代码设置方式似乎是在用户单击注释字段时触发要提交的注释。我认为这不是理想的行为,当用户在评论文本区域字段中按下回车键时(例如在Facebook上),您更可能想要触发提交,在这种情况下,您可能希望使用&#34; KEYUP&#34;事件处理程序然后,您的提交功能将检查是否是按下的输入键,否则不执行任何操作。

$(".post-new-comment-input").on("keyup", function (event) {
    if (e.keyCode == 13) {
        [YOUR AJAX POST CODE HERE]
    } else return false;
});

话虽如此,我不确定用户看到没有提交按钮的表单是多么直观(对于非技术人员的精明......)如果你确实想要包含“提交”按钮并且让它以任何方式工作,您可以将代码放入提交的单独事件处理程序中,然后在用户按下文本区域中的回车键时触发提交事件。

答案 1 :(得分:0)

如果我是你,我会将事件附加到表单元素的提交事件。

要防止默认事件,您应该从函数返回false。或者你可以做event.preventDefault()。

但是在提交事件中这样做是正确的方法。我认为! :)