0

我在这个 jsfiddle 中有一个输入元素:http: //jsfiddle.net/stevea/DLe3a/9。如果我在字段中输入内容后输入 Return,我会触发更改处理程序并拾取并显示该值:

$(function() {
    $('input#fname').change(function(e) {
        $('div#firstName').append(this.value);
    });

但是如果用户忘记点击返回并关闭页面怎么办?在那种情况下,当我感觉到页面关闭时,我想回来,并在没有返回的情况下拉出输入到输入字段中的内容。

我可以这样做吗?在 jsfiddle 我有一个按钮和它的处理程序。假设单击按钮正在关闭页面,我将如何响应按钮单击以获取位于输入字段中的值?

谢谢

4

4 回答 4

0

The problem isn't detecting a page closing down. The problem is to capture an Input field's content when something external happens before the user enters Return. But after playing around with it more, at this jsfiddle - http://jsfiddle.net/stevea/bT54M/3/ - it turns out that there really is no problem. If you're in the middle of entering text into an Input field and you do something external, like hitting the Get Input button in the jsfiddle above, the change event for the Input is triggered automatically and this.value is what you've entered so far. So the bottom line is that you don't need to hit Return when you're done. Just about anything you do outside of the Input (probably anything that blurs the Input focus) triggers the Input change event.

$(function() {

    $('input#fname').change(function(e) {
        debugger;
        $('div#firstName').append(this.value);
    });

    $('#getInput').click(function() {
         debugger;
         $('div#firstName').append(this.value);

    });
});
于 2013-09-02T19:34:09.563 回答
0

试试这个先生

   $(function() {
    $("#fname").change(function(e) {
        $("#firstName").append(this.value)
    });

    $("#getInput").click(function (e)  {
    });
});
于 2013-09-02T02:39:00.917 回答
0

要检测页面是否正在关闭,请使用.unload()事件

$(window).unload(function() {
    var input = $('#fname').val();
});
于 2013-09-02T02:42:49.277 回答
0

我相信你想在窗口预先关闭时做一些代码。

这是一些示例代码:jsDiddle

$('#fname').change(function () {
    $('#firstName').append(this.value);
});

window.onbeforeunload = function (e) {
    var e = e || window.event;
    // get input #fname
    $('#firstName').append($('#fname').val());
    // do something you want before the window closes

    // show confirm message (optional) - if you don't want show message, return '';
    //IE & Firefox
    if (e) {
        e.returnValue = 'You have some unfilled inputs!';
    }

    // For Safari
    return 'You have some unfilled inputs!';
};
于 2013-09-02T02:49:04.657 回答