JQUERY保持绑定点击功能

时间:2012-01-26 11:08:18

标签: jquery events plugins

html:

<div id='myform'>
    Name : <input type='text'/>
    Age : <input type='text'/>
    .....
    <input type='button' class='mysavebutton' value='save'/>
</div>

html脚本:

$(document).ready(function(){
    $("#myform input:button").click(function(){
        //do save
        alert("Save complete.");
    });  
});

问题是: 如何将函数添加到#myform输入:按钮之前“执行保存”而不更改上面的任何代码..(如添加插件)

我已经创造了像这样的东西

$(document).ready(function () {
    $(".mysavebutton").each(function () {
        $(this).data("old_click", $(this).click); // <----- here the problem #1. how to keep click function.

        $(this).unbind("click").click(function () {
            parent = $(this).parents("body");

            $(parent).find("input:textbox").each(function () {
                validate_object(this); //this function validate all textbox on body and add error class to textbox if error
            });

            if ($(parent).find("input:type.error").length == 0) {
                //no error. than call old function
                $(this).data("old_click");  //eval($(this).data("old_click"))
            }
            else {
                 //not run old_click coz error
                alert("Invalid data.")
            }
        });
    });
});

如果可能的话,修理。如果没有,请提供其他解决方案。感谢名单

3 个答案:

答案 0 :(得分:1)

$(document).ready(function () {
  $(".mysavebutton").each(function () {
    $(this).data("old_click", $(this).data('events')['click'][0].handler);

    $(this).unbind("click").click(function () {
        //get the form
        var parent = $(this).closest('form');

        $(parent).find("input:textbox").each(function () {
            validate_object(this); //this function validate all textbox on body and add error class to textbox if error
        });

        if ($(parent).find("input:type.error").length == 0) {
            //no error. than call old function
            $(this).data("old_click").apply(this, arguments);
        }
        else {
             //not run old_click coz error
            alert("Invalid data.")
        }
    });
});
});

可能是更好的方法,但这应该有用。

http://jsfiddle.net/GhLSS/1/

答案 1 :(得分:1)

$(".mysavebutton").each(function(){
    var self = $(this);
    var old_click_handler = self.data('events')['click'][0].handler;
    self.unbind("click").click(function () {
        alert('pre save');
        old_click_handler();
    });    
});

答案 2 :(得分:0)

一个简单的解决方案可能是将您的辅助触发器放在mouseup上,因为它会在点击之前触发:http://www.quirksmode.org/js/events_mouse.html

相关问题