开发者

Subscribing multiple handlers to DOM Events with jQuery

I am attempting to subscribe events by the CSS class. I have two handlers, defined as follows:

$(document).ready(function() {
    $('.refresh-cart').click(
        function(e) {
            alert('refreshing');
        });
    
    $('form.ajax').submit(
        function(e) {
            e.preventDefault();
            $.post(
                this.action,
                $(this).serialize(),
                function(data, textStatus, jqXHR) { alert('post'); },
                'text');
        }
    );
});

When these handlers overlap, I am not getting the expected functionality.

This code works correctly, by alerting 'post' and submitting an ajax request.

 <fo开发者_运维百科rm action="page.html" method="post" class="ajax">
     <input type="text" name="Sample" value="SampleValue" />
     <input type="submit" />
 </form>

This code works correctly, by alerting 'refreshing'

  <div class="refresh-cart">Refresh Widget</div>

However, when these overlap (such as in the following example), only the 'refresh-cart' subscriber fires.

 <form action="page.html" method="post" class="ajax">
     <input type="text" name="Sample" value="SampleValue" />
     <input type="submit" class="refresh-cart" />
 </form>

What am I doing wrong and how can I make both handlers fire?


It works just fine for me..

You do have to close the first alert box, though, before the second can be shown..

your code live at http://jsfiddle.net/gaby/W3zC4/


Have you tried submitting the form from the click handler?

$(document).ready(function() {
    $('form.ajax').submit(
        function(e) {
            e.preventDefault();
            $.post(
                this.action,
                $(this).serialize(),
                function(data, textStatus, jqXHR) { alert('post'); },
                'text'
            );
    });

    $('.refresh-cart').click(
        function(e) {
            alert('refreshing');
            $('form.ajax').submit();
            return false;
     });
});


It works fine for me as well. I think you should also consider jquery form plugin here for ajax submit and changing the input type from submit to button

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜