修改 jquery-modal 事件中的变量值

Modify variable value inside a jquery-modal event

我正在尝试修改 BEFORE_CLOSE 事件中变量的值,到目前为止没有成功...我正在使用 Kylefox's Jquery-modal

HTML:

<div id="other" class="modal" style="display:none;">
<label for="form_otherName" class="label-important required">(*) Enter 'Other' Name </label>
<input type="text" required="required" name="form[otherName]" class="round default-width-input" id="simple-input">
<a href="#close" rel="modal:close">Close window</a></div>

Js:

      $('#form_submit').on('click', function (e) {
        e.preventDefault();
        var page = $("#carousel").rcarousel("getCurrentPage");
        var employeeID = $("input[name='form[employeeID]']").val();
        var temp = '';
       if (page == 4) {
            $('#other').modal();
            $('#other').on($.modal.BEFORE_CLOSE, function (event, modal) {
                temp = $("input[name='form[otherName]']").val();
                console.log(temp);
            });
            console.log('after event '+temp);
            $.post("{{ path("working_letter_model",{'language': 'spanish'})}}", {model: page, idNumber: employeeID}, function (data) {
                //do whatever with the response

                });
            }
}

我做错了什么?有办法解决这个问题吗?

我读到有关 Js 使用变量而不是引用来获取值,但我不知道这是否适用。

您分配临时变量的方式没有任何问题,只是您记录它的方式有问题。看起来您正在阅读这段代码并期望它以线性方式执行,即按照它出现的顺序执行。这是实际发生的事情。

事件在此处注册,并提供回调以在事件触发时执行。

$('#other').on($.modal.BEFORE_CLOSE, function (event, modal) {
    //this code does not execute yet!
    temp = $("input[name='form[otherName]']").val();
    console.log(temp); //it shows the value
});

接下来执行这一行,temp还是有初始值。

console.log('after event '+temp); //it returns empty

最后,当模式关闭时,执行回调,您从中获取控制台日志,其中显示了新分配的值。

temp = $("input[name='form[otherName]']").val();
console.log(temp); //it shows the value