如何将参数传递给回调函数而不执行它

Gor*_*vic 2 javascript jquery callback

我正在使用这个脚本: https://github.com/goranefbl/jquery.tiny.modal/blob/master/jquery.tinymodal.js

在我的一项按下按钮时触发的函数中,这个:

    function fireLightbox(quarter,room_id,otherRoom) {
        $.tinyModal({
            title: "Room is free, want to book now?",
            html: '#bookRoom',
            buttons: ["Book"],
            Book: bookTheRoom(quarter) // <- the issue 
        });
    }
Run Code Online (Sandbox Code Playgroud)

上面灯箱内出现的“书籍”按钮应该执行下面的函数,但是当上面的函数加载时它会立即触发。

    function bookTheRoom(quarter) {
        console.log(quarter);
    }
Run Code Online (Sandbox Code Playgroud)

我需要它。单击按钮后执行,而不是执行第一个“fireLightbox”函数后执行。

也尝试过这样,它不执行它,但也不传递变量,尽管这对我来说是有意义的,它不起作用

function fireLightbox(quarter,room_id,otherRoom) {
    $.tinyModal({
        title: "Room is free, want to book now?",
        html: '#bookRoom',
        buttons: ["Book"],
        Book: function(quarter) {
            console.log(quarter);
            bookTheRoom(quarter);   
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

当然,如果我不带 () 调用它,函数就可以正常工作,但我没有参数。

Gio*_*Gio 5

您可以返回一个函数,然后您传入的变量将通过闭包可供内部函数使用。

function bookTheRoom(quarter)
{
    return function()
    {
        console.log(quarter);
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑 - 详细说明一下:当您调用 时bookTheRoom(quarter),现在它不会console.log直接执行。相反,它返回一个在调用时将执行的函数console.log。这有点像上面的第二个解决方案,其中您将“Book”属性与函数关联 - 区别在于您通过函数调用来执行此操作,因此单击执行的函数可以访问之前的所有变量。传递给您的第一个函数调用。

我的回答旨在作为“通用”解决方案。在您的特定情况下,由于您似乎没有更改季度的值,因此您甚至不需要这样做。你的第二个解决方案已经足够好了,只需quarter从函数定义中删除参数,你的内部函数将通过闭包从外部函数的范围中获取它。需要明确的是,如果quarter不是一个对象并且您没有quarter在内部进行更改fireLightBox(或者即使它是一个对象并且您没有在任何地方更改它),这也可以工作:

function fireLightbox(quarter,room_id,otherRoom) {
    $.tinyModal({
        title: "Room is free, want to book now?",
        html: '#bookRoom',
        buttons: ["Book"],
        Book: function() {
            console.log(quarter);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)