jQuery 中两个按钮的功能相同
我有两个按钮:btnAdd
和 btnUpdate
。我为按钮 btnUpdate
编写了一个 jquery 函数来验证网页中的某些字段,例如:
$(function() {
$('#<%=btnUpdate.ClientID %>').click(function() {
code here
});
});
我想在单击 btnAdd
时执行相同的操作。所以我必须为 btnAdd 再次编写相同的函数。还有其他方法可以避免这种情况吗?
(如果我编写一个 javascript 函数并在两个按钮的按钮单击事件中调用相同的函数,那就没问题。但是有没有办法使用 jQuery?)
I have two buttons: btnAdd
and btnUpdate
. I have written a jquery function for button btnUpdate
to validate some fields in the web page like:
$(function() {
$('#<%=btnUpdate.ClientID %>').click(function() {
code here
});
});
I want to do the same thing when btnAdd
is clicked. So I have to write the same function again for btnAdd. Is there other way to avoid this?
(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?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需选择两个按钮,以逗号分隔:
("#add, #update").click...
在您的代码中看起来像这样:
Just make a selection of two buttons, separated by a comma:
("#add, #update").click...
Looks like this in your code:
有两种方法。
(1) 一次选择两个元素并对它们应用事件处理程序:
(2) 为函数命名,而不是保持匿名:
There are two ways.
(1) Select both elements at once and apply the event handler to them:
(2) Give the function a name, rather than leaving anonymous:
我们称之为重构,它将全程为您提供帮助,了解更多有关投资自己的信息,并购买独一无二的绝佳产品重构书
在你的情况下,你应该这样做:
正如你应该总是这样做。
但作为 jQuery,你可以拥有具有多个输入的选择器,所以你需要做的就是:
We call this Refactoring and it's something that will help you all the way, read more about, invest in yourself and buy the fantastic one and only Refactoring book
in your case, you should do this:
As you should always do.
but as jQuery you can have selectors with multiple inputs, so all you need to do is:
jQuery 是一个 JavaScript 框架,而不是另一种语言,因此您也可以在这里编写一个 JavaScript 函数。
jQuery is a JavaScript framework, not another language, so you can write one JavaScript function here too.