将需要参数的匿名函数传递给另一个函数作为将分配给onclick的参数 [英] Pass Anonymous function that requires a parameter, to another function as an argument which will be assigned to an onclick

查看:48
本文介绍了将需要参数的匿名函数传递给另一个函数作为将分配给onclick的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个我希望在整个程序中重用的功能。基本上它是一个带有确认和取消按钮的引导对话框。我设置了辅助函数来接受两个匿名函数,一个用于取消,一个用于确认。我有一切工作,但我不知道如何在构建HTML时正确地将它分配给onclick。我想避免使用全局变量,但这是我能够使其工作的唯一方法。

I have a function that I want to reuse throughout my program. Basically it's a bootstrap dialog box that has a confirm and a cancel button. I setup the helper function to accept two anonymous functions, one for the cancel and one for the confirm. I have everything working except I am not sure how to properly assign it to the onclick when building the html. I want to avoid using a global variable but this is the only way I was able to get this to work.

自定义函数:

    function confirmMessageBox(msg, cancelFunc, confirmFunc) {
    var html = ' <div class="container"><div class="modal fade" id="ConfirmMsgModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Confirmation Needed</h4></div><div class="locationTableCanvas"><div class="modal-body"><p>' + msg + '</p></div></div><div class="modal-footer"><table><tr><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "(' + cancelFunc + ')()">Cancel</button></td><td><button type="button" class="btn btn-default" data-dismiss="modal" onclick = "(' + confirmFunc + ')()">Confirm</button></td></tr></table></div></div></div></div></div>';
    $("#confirmMsgContainer").html(html);
    $('#ConfirmMsgModal').modal('show');
}

我必须这样做,onclick =('+ cancelFunc +')( )>因为如果我这样做,onclick ='+ cancelFunc()+'>它显示为未定义。目前的方法基本上只是打印匿名函数并将其分配给onclick(几乎就像我刚刚在onclick上输入匿名函数)

I have to do, onclick = "(' + cancelFunc + ')()"> because if I do, onclick = "' + cancelFunc() + '"> it shows up as undefined. The current way will basically just print the anonymous function out and assign it to the onclick (almost as if I just typed out the anonymous function right at the onclick)

这里是我在哪里调用函数:

here is where I call the function:

    var transTypeHolder;
$("input[name='transType']").click(function () {
    var tabLength = $('#SNToAddList  tbody  tr').length;
    if (tabLength == 0) {
        var selection = $(this).attr("id");
        serialAllowableCheck(selection);
        resetSerialNumberCanvasAndHide();
        $("#Location").val("");
        $("#SerialNumber").val("");
    }
    else {
        transTypeHolder = $(this).val();
        var confirm = function () {

            var $radios = $('input:radio[name=transType]');
            $radios.filter('[value='+transTypeHolder+']').prop('checked', true);
            resetSerialNumberCanvasAndHide();
            $('#Location').val('');
            $('#SerialNumber').val('');
        };
        var cancel = function () {};
        confirmMessageBox("This is a test", cancel, confirm);
        return false;
    }

});

有没有办法在不使用全局变量的情况下将变量传递给匿名函数as,transTypeHolder?

Is there a way to some how pass a variable to the anonymous function without using the global variable I have as, "transTypeHolder" ?

在我得到之前,你为什么要这样做?响应; Javascript不是我的强语,因为我使用的是ASP.NET MVC4。我没有机会坐下来详细学习Javascript,我有点挑选它并搜索我需要的东西。因此,如果有更好的解决方法,我愿意接受建设性的批评。

Before I get the, "Why are you doing it this way??" response; Javascript isn't a strong language of mine, as I am using ASP.NET MVC4. I haven't had a chance to sit down and learn Javascript in detail and I sort of picked it up and search what I need. So if there is a better way of tackling this, I am open for constructive criticism.

推荐答案

不要在HTML中进行事件处理程序分配。如果您希望人们能够提供他们自己的功能来取消和确认使用

Don't make event handler assignments in HTML at all. If you want people to be able to supply their own functions for canceling and confirming use on:

function confirmMessageBox(msg, cancelFunc, confirmFunc) {
    var html = ' <div class="container"><div class="modal fade" id="ConfirmMsgModal" role="dialog"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Confirmation Needed</h4></div><div class="locationTableCanvas"><div class="modal-body"><p>' + msg + '</p></div></div><div class="modal-footer"><table><tr><td><button type="button" class="btn btn-default cancel" data-dismiss="modal">Cancel</button></td><td><button type="button" class="btn btn-default confirm" data-dismiss="modal">Confirm</button></td></tr></table></div></div></div></div></div>';
    $("#confirmMsgContainer").html(html);
    $("#confirmMsgContainer").off('click', '.confirm').on('click', '.confirm', confirmFunc);
    $("#confirmMsgContainer").off('click', '.cancel').on('click', '.cancel', cancelFunc);
    $('#ConfirmMsgModal').modal('show');
}

请注意,我已经编辑了您用来删除<的HTML code> onclick s并为每个按钮添加了一个类。我还使用 off 来确保删除任何以前添加的事件处理程序。

Note that I've edited the HTML you're using to remove the onclicks and added a class to each button. I'm also using off to be sure any previously added event handlers are removed.

至于传递如果不使用全局变量到confirm函数,请使用闭包:

As far as passing the variable to the confirm function without using a global, use a closure:

var transTypeHolder = $(this).val();
var confirm = (function (typeHolder) { 
    return function () {
        var $radios = $('input:radio[name=transType]');
        $radios.filter('[value='+typeHolder+']').prop('checked', true);
        resetSerialNumberCanvasAndHide();
        $('#Location').val('');
        $('#SerialNumber').val('');
    };
})(transTypeHolder);

这告诉JavaScript创建一个函数,它返回一个执行你想要它做的事情的函数。那个函数创建者接受你想要保留的变量,允许它在其他地方使用。

That tells JavaScript to create a function, which returns a function that does what you want it to do. That "function creator" takes in the variable you want to keep around, allowing it to be used elsewhere.

现在,我没有测试过这个,所以你可能有在你的未来进行一些调试,但希望它能为你提供一个起点。

Now, I haven't tested this, so you may have some debugging in your future, but hopefully it gives you a jumping-off point.

这篇关于将需要参数的匿名函数传递给另一个函数作为将分配给onclick的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆