简体   繁体   English

使用JavaScript的通用类对象侦听器遇到麻烦了吗?

[英]Trouble with a common-class object listener in Javascript?

I have the following Javascript: 我有以下Javascript:

function save_data_check(e) {
    var input_value = $('.input-right').text();

    if (input_value !== "") {

        if(!e) e = window.event;
        e.cancelBubble = true;
        e.returnValue = 'You have unsaved data on this page.'; 

        if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();

        }

    }

}

window.onbeforeunload = save_data_check;

The intended function of this code is to run the function 'save_data_check' when the user tries to leave the page if any input with the common class 'input-right' has any value. 该代码的预期功能是,当用户尝试离开页面时,如果具有公共类“ input-right”的任何输入具有任何值,则该函数将运行“ save_data_check”功能。

The problem with this function seems to be the most basic part of it: the event listener. 这个函数的问题似乎是它最基本的部分:事件监听器。 Removing the if statement checking if there is any value to the common-class inputs yields the pop-up everytime I try to leave the page? 删除if语句以检查通用类输入是否有任何值会在每次尝试离开页面时弹出该弹出窗口吗?

How am I failing to listen to this event? 我如何无法收听此事件?

There are two problems: 有两个问题:

  1. onbeforeunload is an unusual event. onbeforeunload是一个不寻常的事件。 You simply return the message you want displayed. 您只需返回要显示的消息。

  2. input elements don't have text, they have a value . input元素没有文本,它们有一个

So: 所以:

function save_data_check() {
    var msg;

    $('.input-right').each(function() {
        if (this.value) {
            msg = 'You have unsaved data on this page.';
            return false;
        }
    });

    return msg;
}

window.onbeforeunload = save_data_check;

Live Example 现场例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM