jQuery,使用多个事件触发器?

时间:2016-12-02 14:36:51

标签: jquery

我有一个HTML表,我填充了数据库表中的信息。我已经使表格中的单元格在单击时可编辑,并且在单元格完成编辑时添加了jQuery(最后一次按键后2.5秒),然后ajax将信息发送到单独的php文件以更新数据库表格值。我发现的一个问题是,如果单击该单元格进入另一个单元格并在这些2.5秒之前进行更改,则第一个更改永远不会更新到数据库。

我的问题是:如果我改为使用字段模糊事件,有没有办法让我仍然可以合并定时器,以便在字段模糊或超时时达到ajax达到?

$('td').on('input', function() {
    var _this = $(this); // preserve reference to the input field here

    if(saveTimeout) clearTimeout(saveTimeout);
    saveTimeout = setTimeout(function() {
        console.log(_this)
        $.ajax({
            method: "POST",
            url: "updatedatabase.php",
            data: { 
                content: _this.text(), 
                date: _this.siblings().first().text(),
                prod: $('tr:first-child th:nth-child(' + (_this.index() + 1) + ')').text(),
                old: old
            }
        })
        .done(function( msg ) {
            alert( msg );
        });

    }, 2500);
});

1 个答案:

答案 0 :(得分:1)

我建议您使用不同的.setTimeout延迟,具体取决于触发它的事件。

所以在blur上,它不会等待2.5秒才能保存,就像在input上一样。

<强> EDITED
要防止&#34;双重保存&#34;,请将td标记为已保存。

var saveTimeout;

// Remove the "saved" class on keydown
$('td').on('keydown', function(e) {
    $(this).removeClass("saved");
});

$('td').on('input blur', function(e) {
    console.log("event "+e.type+" occured");
    var timeoutDelay=2500;

    if( e.type == "blur" ){
        timeoutDelay=1;
    }

    // If NOT already saved...
    if( !$(this).hasClass("saved") ){
        var _this = $(this); // preserve reference to the input field here

        clearTimeout(saveTimeout);
        saveTimeout = setTimeout(function() {
            console.log(_this);

            $.ajax({
                method: "POST",
                url: "updatedatabase.php",
                data: { 
                    content: _this.text(), 
                    date: _this.siblings().first().text(),
                    prod: $('tr:first-child th:nth-child(' + (_this.index() + 1) + ')').text(),
                    old: old
                }
            })
            .done(function( msg ) {
                alert( msg );
                // Add the "saved" class to prevent other saving
                _this.addClass("saved");
            });

            console.log("Ajax sent");

        }, timeoutDelay);
    }
});