如何将“$(this)”作为参数传递给Javascript中的“callready”函数

How to pass `$(this)` as parameter to a "callready" function in Javascript

本文关键字:参数传递 Javascript 中的 函数 callready this      更新时间:2023-09-26

leanModal函数触发带有一些参数的模态。其中一个参数是一个函数(ready),一旦Modal打开就会被执行。关键是,我需要在该函数(ready)中仅使用触发模态的元素(tag)做一些事情,因此我需要$(this)作为参数传递给该函数。leanModal()函数由MaterializeCss提供,这是我正在使用的框架。

我一直在尝试这个,但thisTag总是不确定的。我也尝试将$(this)直接传递给函数,但它也根本不起作用,它仍然未定义。那么,我怎样才能达到这个目标呢?

$('.modal-trigger-editMedic').leanModal({
    thisTag: $(this),
    ready: function(thisTag){
        var refereeNum = thisTag.siblings("[name*='refereeNumToEdit']" )[0].value;
        $('#surname').val($("input[id*='medicNameToModal"+refereeNum+"'").val());
    }
});

遵循源代码,.leanModal支持一个就绪函数(一旦模态可见就会触发),但不绑定或发送触发模态的元素,解决此问题的最简单方法是在外部存储引用。为此,您需要自己迭代触发器,而不是依赖此jQuery插件提供的功能。

这样:

var $surname = $('#surname'); // you should store the selector as a reference 
                              // outside the loop for better performance
$('.modal-trigger-editMedic').each(function() {
    var $this = $(this); // this is the current item in the set of elements, 
                         // therefore our trigger element
                         // EDIT: using var makes this a local variable
    $this.leanModal({
        ready: function() {
            var refereeNum = $this.siblings("[name*='refereeNumToEdit']" )[0].value;
            $surname.val($("input[id*='medicNameToModal"+refereeNum+"'").val());
        }
    });
});

当你在精益模态中时,它变成了这个。尝试将 var 设置为 $(this) 并将其传递。

var that = $(this);
$('.modal-trigger-editMedic').leanModal({
    thisTag: that,
    ready: function(thisTag){
        var refereeNum = thisTag.siblings("[name*='refereeNumToEdit']" )[0].value;
        $('#surname').val($("input[id*='medicNameToModal"+refereeNum+"'").val());
    }
});