开发者

Jquery button.click bug?

I have the following home-grown jquery plugin:

(function($) {
    $.fn.defaultButton = function(button) {
        var field = $(this);
        va开发者_运维技巧r target = $(button);

        if (field.attr('type').toLowerCase() != 'text')
            return;

        field.keydown(function (e) {
            if ((e.which || e.keyCode) == 13) {
                console.log('enter');
                target.click();
                return false;    
            }
        });    
    }
})(jQuery);

I'm using it like so:

$('#SignUpForm input').defaultButton('#SignUpButton');

$('#SignUpButton').click(function(e) {
    console.log('click');
    $.ajax({
        type: 'post',
        url: '<%=ResolveUrl("~/WebServices/ForumService.asmx/SignUp")%>',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        data: JSON.stringify({
            email: $('#SignUpEmail').val(),
            password: $('#SignUpPassword').val()
        }),
        success: function(msg) {
            $.modal.close();
        }
    });
});

The first time, it works. The second time, nothing happens. I see enter and click the first time in the firebug log, but the second time I only see the enter message. It's almost like the button's click handler is being unregistered somehow. Any thoughts?


Sounds very much like there's something in the ajax success handler that's modifying the part of the DOM containing the #SignUpButton and thus killing all event handlers associated with it. Try the live method instead:

$('#SignUpButton').live('click', function(e) {
    ...
});


You're probably resetting the HTML containing the button, which will re-create the <button> element from scratch (without any event handlers).

To fix this, you can add the event handler using the live function, which will handle the event on all elements matching the selector, no matter when they were created.


Not answering the question, but you should make this chainable, as it's a useful plugin :)

(function($) {
  $.fn.defaultButton = function(selector) {
    if (this.attr('type').toLowerCase() != 'text')
        return this;
    this.keydown(function (e) {
        if ((e.which || e.keyCode) == 13) {
            console.log('enter');
            $(selector).click();
            return false;    
        }
    });
    return this; 
  }
})(jQuery);

Also, note that this is already a jQuery object, no need to clone it.
Making this wiki, feel free to improve it :)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜