简体   繁体   English

如何使用jQuery处理两个不相关的事件

[英]How to handle two unrelated events with jquery

I'm wondering if I can fire off both of these events together : 我想知道是否可以同时触发这两个事件:

$("input[type=checkbox]").click(function(){
   if($(this).is(":checked"))
   {
       //Value of checkbox
       alert(this.value);
   }
});

and

$("input[type= 'text']").keyup(function(){
   alert(this.value);
});

I looked into .bind, but that seems to only work for one selected elements (ie $(p).bind("mouseout mouseenter).doSomething()) . 我研究了.bind,但这似乎仅适用于一个选定的元素(即$(p).bind("mouseout mouseenter).doSomething())

The situation I am running into is that I have a function that needs to fire anytime either one of these things occur. 我遇到的情况是,我有一个函数需要在这些情况之一发生时随时触发。

Try 尝试

$("input[type=checkbox],input[type='text']").on('click keyup', function(){
   // code
});

If you still need the additional if, you can use: 如果仍然需要其他条件,则可以使用:

$("input[type=checkbox]").click(function(){
   if($(this).is(":checked"))
   {
       //Value of checkbox
       alert(this.value);
       somethingHappened();
   }
});

$("input[type= 'text']").keyup(function(){
   alert(this.value);
   somethingHappened();
});

function somethingHappened() {
   // Do stuff
}

Two ways you can achieve this as shown below: 您可以通过两种方式实现这一目标,如下所示:

  1. using "on" method: 使用“ on”方法:

     $(document).on('keyup click',"input[type=checkbox],input[type='text']", function(){ // Do stuff here.. }) 
  2. Call function after the event. 事件结束后调用函数。

     $("input[type=checkbox]").click(doSomething); $("input[type= 'text']").keyup(doSomething); function doSomething() { } 

Perhaps all you need is a common function? 也许您只需要一个通用功能?

$("input[type=checkbox]").click(function(){
   if($(this).is(":checked")) {
       special(this.value);
   }
});

$("input[type= 'text']").keyup(function(){
   special(this.value);
});

function special(val) {
   alert(val);
}

If your intent really is to invoke a function when any checkboxes/text fields across the whole page changes, you probably want something like this: 如果您的意图实际上是在整个页面上的任何复选框/文本字段发生更改时调用一个函数,那么您可能想要这样的事情:

$('body').on('change', ':checkbox,:text', function () {


});

Note that the :checkbox and :text selectors are much nicer than input[type=checkbox] etc. 请注意, :checkbox:text选择器比input[type=checkbox]等更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM