如何在链接点击事件jquery中调用onbeforeunload?

时间:2014-04-22 09:57:45

标签: jquery

我有带有文本框的div标签,在div之外我有一个链接按钮。 *我使用dataTable js并添加自定义列作为“编辑”链接,其href =“#”..

  1. 如果我点击链接而不输入任何数据意味着它不应该调用onbeforeunload函数。

  2. 在单击保存之前在文本框中输入任何数据如果单击链接意味着它应该调用onbeforeunload函数。并且必须显示“您还没有保存更改”的消息。

  3. <div id="inputform">Description
      <input type="text" id="Description" placeholder="Enter the description..." name="description" />
      <input type="submit" value="save"/>
    </div>
    <a href='www.google.co.in'>link</a>                                   
    
    $('#inputform').on('change keyup keydown', 'input, textarea, select', function (e) {
        $(this).addClass('changed-input');
    });
    
    $(window).on('beforeunload', function () {
        if ($('.changed-input').length) {
            return 'You haven\'t saved your changes.';
        }
    });
    

    http://jsfiddle.net/4fNCh/809/

1 个答案:

答案 0 :(得分:1)

使用变量ie saved来跟踪是否单击了保存按钮。您可以在卸载事件中检查:

Fiddle

var saved = true;

$(function () {
    $('input[type=submit]').click(function () {
        // do the saving...
        saved = true;
    });

    $('#inputform').on('change keyup keydown', 'input, textarea, select', function (e) {
        $(this).addClass('changed-input');
        saved = false;
    });

    $(window).on('beforeunload', function () {
        if (!saved) {
            if ($('.changed-input').length) {
                return 'You haven\'t saved your changes.';
            }
        }
    });
    $(document).on('click', 'a[href]', function () {
        if (!saved) {
            if ($('.changed-input').length) {
                return confirm('You haven\'t saved your changes.');
            }
        }
    });
})