Iva*_*van 9 checkbox jquery load function click
在我的"更新"页面中,我经常需要在页面加载和单击某个复选框上调用相同的jQuery函数,大多数情况如下:
function foo(){
if ($('#mycheckbox').is(':checked')){
$('.myclass').hide();
} else {
$('.myclass').show();
}
}
$(function() {
foo(); // this is launched on load
$('#mycheckbox').click(function(){
foo(); // this is launched on checkbox click
})
});
Run Code Online (Sandbox Code Playgroud)
在页面加载时,可以根据数据库值检查或不检查复选框:这就是为什么我需要启动foo(); 负载
嗯,这很好,但我总是想知道......是否有更好或最优雅的解决方案?提前致谢
您可以使用该trigger()
功能立即触发事件;
$('#mycheckbox').click(function (){
if ($('#mycheckbox').is(':checked')){
$('.myclass').hide();
} else {
$('.myclass').show();
}
}).trigger('click');
Run Code Online (Sandbox Code Playgroud)
但是,请记住,这也会触发您在元素上定义的任何其他单击处理程序.
或者,您可以编写一个小的jQuery插件来为您完成;
jQuery.fn.nowAndOn = function (event, handler) {
handler();
this.bind(event, handler);
return this; // support chaining
};
Run Code Online (Sandbox Code Playgroud)
而且你会喜欢它;
$(function() {
$('#mycheckbox').nowAndOn('click', function (){
if ($('#mycheckbox').is(':checked')){
$('.myclass').hide();
} else {
$('.myclass').show();
}
});
});
Run Code Online (Sandbox Code Playgroud)
但是,这个问题是在click处理程序中,this
通常是当前元素; 而通过调用handler();
就像我们在这里做的那样,this
会指向window
(这与您发布的确切片段无关,因为您不使用this
).
要修复this
,我们可以添加一些复杂性并使用该Function.call
方法来设置值this
;
jQuery.fn.nowAndOn = function (event, handler) {
this.each(function () {
handler.call(this);
});
this.bind(event, handler);
return this;
};
Run Code Online (Sandbox Code Playgroud)
但是,如果依赖于传递的Event对象,您仍然会遇到问题...
你能做的最好的就是:
$(function() {
foo(); // this is launched on load
$('#mycheckbox').click(function(){
foo(); // this is launched on checkbox click
})
});
Run Code Online (Sandbox Code Playgroud)
- >
$(function() {
foo(); // this is launched on load
$('#mycheckbox').click(foo);
});
Run Code Online (Sandbox Code Playgroud)