简体   繁体   English

是否可以在不执行click事件的情况下执行内联单击事件功能?

[英]Is it possible to execute an inline click event function without executing a click event?

Explaining by example: 通过例子解释:

$(".myCheckboxes").click(function () {
    ...
});

Inside the click event function I have code that does various things depending on what checkboxes are checked. 在click事件函数中,我有代码可以执行各种操作,具体取决于选中的复选框。

I however need to run this code to initialize it first, kindof like this: 但是我需要先运行此代码来初始化它,有点像这样:

$(".myCheckboxes").click(function () {
    ...
}).click();

It runs the code and it gets initialized, but it also clicks on all my checkboxes making them all invert their value. 它运行代码并初始化,但它也点击我的所有复选框,使它们都反转它们的值。

Is it possible to execute the inline click event function wihtout executing a click event? 是否可以执行内联点击事件功能而不执行点击事件?

I would very much like to keep the function inline to keep the flow of the code. 我非常希望保持函数内联以保持代码流。 Also, it's not big enough to have the function outside of the event, but it's not so small as I would like to write the code twice. 此外,它不足以让事件在事件之外,但它并不像我想要编写代码两次那么小。

Use a named function as the handler, bind it and execute it: 使用命名函数作为处理程序,绑定它并执行它:

$(".myCheckboxes").click(clickHandler);
clickHandler();

triggerHandler triggers only the handler: triggerHandler仅触发处理程序:

$(".myCheckboxes").click(function () {
    ...
}).each(function(i, checkbox) { 
    $(checkbox).triggerHandler('click'); 
}

Note that you need to iterate the checkboxes if you wish to trigger the handler for all of them instead of just the first one: 请注意,如果您希望触发所有这些复选框而不是第一个复选框,则需要迭代复选框:

while .trigger() will operate on all elements matched by the jQuery object, .triggerHandler() only affects the first matched element. 而.trigger()将对jQuery对象匹配的所有元素进行操作,而.triggerHandler()只影响第一个匹配的元素。

You may consider to call the function triggerHandler who seems to do what you need. 你可以考虑调用似乎做你需要的函数triggerHandler

$(".myCheckboxes").click(function () {
...
}).triggerHandler('click');

NB: I haven't tested this solution. 注意:我还没有测试过这个解决方案。

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

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