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

时间:2015-10-29 11:14:49

标签: 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 
        });
    }

&#34;图书&#34;出现在上面灯箱内的按钮应该执行以下功能,但是当上面的功能加载时它会立即触发。

    function bookTheRoom(quarter) {
        console.log(quarter);
    }

我需要它。我点击按钮后执行,而不是第一个&#34; fireLightbox&#34;功能被执行。

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

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

当然,如果我在没有()的情况下调用函数,函数可以正常运行,但是我没有参数。

1 个答案:

答案 0 :(得分:4)

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

function bookTheRoom(quarter)
{
    return function()
    {
        console.log(quarter);
    }
}

编辑 - 详细说明:当您致电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);
        }
    });
}