jQuery的trigger()和submit()

时间:2014-10-27 12:38:15

标签: jquery

我有一个这样的简单形式:

<form action="">
    <div class="btn">
       <input type="text" name="n" id="form-name">
       <input type="submit" name="go">
    </div>
</form>

<a href="" class="vote" title="test">vote</a>

我尝试从其他按钮(.vote)提交:

var voteButton = section.find('.vote'),
    storyContainer = $('input[name=n]'),
    storySubmit = $('.btn').find('input[name=go]'),
    storyForm = $('.btn').closest('form');

voteButton.each(function() {
    var title = $(this).attr('data-story');

    $(this).on('click', function() {
        $(this).closest('article').animate({opacity: .75},150, function() {
            storyContainer.attr('value', title);
        });

        setTimeout(function() {
            storySubmit.trigger('click');

            storyForm.on('submit', function() {
                alert('bam');
                return false;
            });
        },50);

        return false;
    });
});

我想要的是提交表单(trigger),但阻止它重新加载页面with on('submit')。但它甚至没有转到submit,它会重新加载页面。我该怎么办?

1 个答案:

答案 0 :(得分:1)

以下是使用submit元素触发表单.vote事件的方式:

$(function() {
    $('a.vote').on('click',function(e) {
        e.preventDefault();
        $(this).prev('form').find(':submit').trigger( 'click' );
    });
});

&#13;
&#13;
$(function() {
        $('a.vote').on('click',function(e) {
            e.preventDefault();
            $(this).prev('form').find(':submit').trigger( 'click' );
        });
        $('#myForm').on('submit',function(e) {
            e.preventDefault();
            alert( 'The submit event has fired!' );
        });
    });
&#13;
.btn {
  display:none;
 }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" id="myForm">
    <div class="btn">
       <input type="text" name="n" id="form-name">
       <input type="submit" name="go">
    </div>
</form>

<a href="" class="vote" title="test">vote</a>
&#13;
&#13;
&#13;