页面加载时jQuery绑定事件

时间:2021-05-04 20:24:20

I have a small script that I would like to complete on change of value, on click, or on keyup on certain elements, but I also want it to happen on page load (or when the elements first load).

我有一个小脚本,我想完成更改值,点击或某些元素的键盘,但我也希望它发生在页面加载(或元素首次加载时)。

The code that I have now will do it, but doesn't do it originally on page load, you have to complete one of the 3 triggers first. Is it possible to do this without writing a new script?

我现在的代码将执行此操作,但在页面加载时不执行此操作,您必须先完成3个触发器中的一个。是否可以在不编写新脚本的情况下执行此操作?

$(document).ready(function() {
    $('.orderinput, .paymethod, .serverselect').bind('change click keyup', function(event) {}
});

2 个解决方案

#1


1  

Take your logic out, and put it into a separate function. Then call that function in your ready clause. For example:

把你的逻辑拿出来,把它放到一个单独的函数中。然后在ready子句中调用该函数。例如:

$(document).ready(function() {
    $('.orderinput').on('change click keyup', function(event) { myComplexFunc(event); } );

    var myComplexFunc = function(event) {
        console.log('Triggered');
    }

    myComplexFunc();

});

#2


1  

Along the lines of Mike L, I would suggest you use .on instead of .bind as it is the preferred method for attaching event handlers to a document, see this.

按照Mike L的说法,我建议您使用.on而不是.bind,因为它是将事件处理程序附加到文档的首选方法,请参阅此内容。

If you want to avoid writing a separate function you can trigger an event after the event handler has been attached directly on the element like this:

如果你想避免编写一个单独的函数,你可以在事件处理程序直接附加到元素之后触发事件,如下所示:

$(".yourElementClass").click(); //or .change() or .keyup()

#1


1  

Take your logic out, and put it into a separate function. Then call that function in your ready clause. For example:

把你的逻辑拿出来,把它放到一个单独的函数中。然后在ready子句中调用该函数。例如:

$(document).ready(function() {
    $('.orderinput').on('change click keyup', function(event) { myComplexFunc(event); } );

    var myComplexFunc = function(event) {
        console.log('Triggered');
    }

    myComplexFunc();

});

#2


1  

Along the lines of Mike L, I would suggest you use .on instead of .bind as it is the preferred method for attaching event handlers to a document, see this.

按照Mike L的说法,我建议您使用.on而不是.bind,因为它是将事件处理程序附加到文档的首选方法,请参阅此内容。

If you want to avoid writing a separate function you can trigger an event after the event handler has been attached directly on the element like this:

如果你想避免编写一个单独的函数,你可以在事件处理程序直接附加到元素之后触发事件,如下所示:

$(".yourElementClass").click(); //or .change() or .keyup()