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 input:button 在“do save”之前而不更改上面的任何代码..(如添加插件)
我已经创建了这样的东西
$(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.")
}
});
});
});
如果可能的话,进行修复。如果没有,请给出其他解决方案。感谢x
最佳答案
$(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.")
}
});
});
});
可能是更好的方法,但这应该有效。
关于JQUERY保持绑定(bind)点击功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9017235/