javascript jQuery 中两个按钮的相同功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3810731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
same function for two buttons in jQuery
提问by ANP
I have two buttons: btnAddand btnUpdate. I have written a jquery function for button btnUpdateto validate some fields in the web page like:
我有两个按钮:btnAdd和btnUpdate。我为按钮编写了一个 jquery 函数btnUpdate来验证网页中的某些字段,例如:
$(function() {
$('#<%=btnUpdate.ClientID %>').click(function() {
code here
});
});
I want to do the same thing when btnAddis clicked. So I have to write the same function again for btnAdd. Is there other way to avoid this?
btnAdd单击时我想做同样的事情。所以我必须再次为 btnAdd 编写相同的函数。有没有其他方法可以避免这种情况?
(If I write one javascript function and call the same function in the button click event of both buttons, it's fine. But is there any way using jQuery?)
(如果我编写一个 javascript 函数并在两个按钮的按钮单击事件中调用相同的函数,那很好。但是有没有办法使用 jQuery?)
回答by naivists
Just make a selection of two buttons, separated by a comma: ("#add, #update").click...Looks like this in your code:
只需选择两个按钮,用逗号分隔: ("#add, #update").click...在您的代码中看起来像这样:
$(function() {
$('#<%=btnUpdate.ClientID %>, #<%=btnAdd.ClientID %>').click(function() {
code here
});
});
回答by mpen
There are two ways.
有两种方法。
(1) Select both elements at once and apply the event handler to them:
(1) 同时选择两个元素并将事件处理程序应用于它们:
$(function() {
$('#<%=btnUpdate.ClientID %>, #<%=btnAdd.ClientID %>').click(function() {
code here
});
});
(2) Give the function a name, rather than leaving anonymous:
(2) 给函数一个名字,而不是留下匿名:
function clickHandler() {
// code here
}
$('#<%=btnUpdate.ClientID %>, #<%=btnAdd.ClientID %>').click(clickHandler);
回答by balexandre
We call this Refactoringand it's something that will help you all the way, read more about, invest in yourselfand buy the fantastic one and only Refactoring book
我们称之为重构,它会一直帮助你,阅读更多关于你自己的投资,并购买一本非常棒的并且唯一的重构书
in your case, you should do this:
在你的情况下,你应该这样做:
$(function() {
$('#<%=btnUpdate.ClientID %>').click(function() {
validate($this);
});
$('#<%=btnAdd.ClientID %>').click(function() {
validate($this);
});
});
function validate(myButton)
{
// code here
}
As you should always do.
正如你应该做的那样。
but as jQuery you can have selectors with multiple inputs, so all you need to do is:
但是作为 jQuery,你可以有多个输入的选择器,所以你需要做的就是:
$('#<%=btnUpdate.ClientID %>, #<%=btnAdd.ClientID %>').click(function() {
validate($this);
}
回答by Paul D. Waite
jQuery is a JavaScript framework, not another language, so you can write one JavaScript function here too.
jQuery 是一种 JavaScript 框架,而不是另一种语言,因此您也可以在这里编写一个 JavaScript 函数。
function validateFields(e) {
code here;
}
$(function() {
$('#<%=btnUpdate.ClientID %>').click(validateFields);
$('#<%=btnAdd.ClientID %>').click(validateFields);
});

