Javascript Jquery:同时绑定加载+更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7531347/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:37:23  来源:igfitidea点击:

Jquery: bind load + change simultaneously

javascriptjquery

提问by max

In many cases, I need to bind a behaviour to an element after loading, and then after an event triggering (like "change"). I think the best way would be to make it in the same line:

在许多情况下,我需要在加载后将行为绑定到元素,然后在事件触发后(如“更改”)。我认为最好的方法是将其放在同一行中:

$('#element_id').bind('load, change', function () {
...
});

But this works only for "change" and not for "load". There is a better way?

但这仅适用于“更改”而不适用于“加载”。有一个更好的方法?

回答by johndodo

I stumbled across the same problem. Removing comma is not enough, at least not in this case:

我偶然发现了同样的问题。删除逗号是不够的,至少在这种情况下不是:

$(document).ready(function(){
    $('#element_id').bind('load change', function () {
        ... // (this DOESN'T get called on page load)
    });
});

I guess loadevents get triggered before $(document).ready().

我猜load事件在$(document).ready().

This is a simple solution:

这是一个简单的解决方案:

$(document).ready(function(){
    $('#element_id').bind('change', function () {
        ...
    });
    $('#element_id').trigger('change');
});

回答by stovroz

For already loaded content, when you want to run a function on an event and also straight away, you can use a custom event of your own naming to avoid triggering any existing bindings from libraries etc. on the built in events, e.g.

对于已经加载的内容,当你想在一个事件上运行一个函数并立即运行时,你可以使用你自己命名的自定义事件来避免在内置事件上触发来自库等的任何现有绑定,例如

$(".my-selector").on("change rightnow", function() {
  // do stuff...
}).triggerHandler("rightnow");

回答by DoctorMick

Don't you just need to remove the comma?

你不是只需要删除逗号吗?

回答by DMac the Destroyer

try it without the comma:

尝试不带逗号:

$('#element_id').bind('load change', function () {
...
});

http://api.jquery.com/bind/#multiple-events

http://api.jquery.com/bind/#multiple-events