开发者

Jquery: bind load + change simultaneously

开发者 https://www.devze.com 2023-04-08 12:10 出处:网络
In many cases, I need to bind a behaviour to an element after loading, and then after an event triggering (like \"change\").

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" a开发者_开发百科nd not for "load". There is a better way?


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 load events get triggered before $(document).ready().

This is a simple solution:

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


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");


Don't you just need to remove the comma?


try it without the comma:

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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消