2012-03-29 80 views
3

我有两个jquery的,我跑,我想结合他们两个在同一行。 这是我想要做的一个例子。现在两个jquery函数在同一时间

​$(function(){ 
    $('input').each(function(){ 
     if ($(this).is(':checked')) { 
      $(this).after('this is checked'); 
     } 
    }); 
    $('input').click(function(){ 
     if ($(this).is(':checked')) { 
      $(this).after('this is checked'); 
     } 
    }); 
});​ 

,这两个函数做同样的事情,一个是检查是否有从后端被检查的任何输入执行,另一位刚刚来响应用户点击。

我想如果我能在这样的声明将它们结合起来,

$('input').bind('each click'); 

,但我注意到,即使这会不会各项工作。 任何想法?

谢谢!

回答

1

仅举功能..

function handler() { 
    if ($(this).is(':checked')) { 
     $(this).after('this is checked'); 
    } 
} 

然后在这两种情况下,它使用:

$(function(){ 
    $('input').each(handler); 
    $('input').click(handler); 
});​ 
+0

这个很好用!谢谢 !! – 2012-03-29 19:03:56

1

您不能绑定each方法,因为它不是一个事件。

分配功能给一个变量,这样就可以重复使用它:

​$(function(){ 

    var markChecked = function() { 
    if ($(this).is(':checked')) { 
     $(this).after('this is checked'); 
    } 
    }; 

    $('input').each(markChecked).click(markChecked); 
});​ 

有时用来为每个元素强制初始检查上触发click事件的另一种方法:

​$(function(){ 
    $('input').click(function() { 
    if ($(this).is(':checked')) { 
     $(this).after('this is checked'); 
    } 
    }).click(); 
});​ 

这当然假设触发点击事件没有任何副作用。如果你已经绑定了另一个点击事件处理程序到任何元素,这将导致该事件处理程序也被调用。

+0

这太伟大工程!谢谢 !!! – 2012-03-29 19:04:08