关闭焦点div不激活jQuery函数

时间:2014-04-24 18:12:51

标签: javascript jquery ajax html

这是我的HTML

$html .= "  <td><div class='edit_course' data-id='{$id}' data-type='_title' contenteditable='true'>{$obj->title}</div></td>";

这是我的jQuery

var selector = 'div[contenteditable="true"]';
// initialize the "save" function
$(selector).focus(function(e) {
    content_holder = $(this);
    content = content_holder.html();

    var id = $(this).data('id');
    var type = $(this).data('type');

    alert( id + type)

    // one click outside the editable area saves the content
    $('body').one('click', function(e) {
        // but not if the content didn't change
        if ($(e.target).is(selector) || content == content_holder.html()) {
            return;
        }

        // Edited out AJAX call
    });
});

问题是,当我点击div时,会触发下面的提醒。当我点击div之外(编辑完成后)时,没有任何反应。谁能看到发生了什么?

首先点击让用户编辑div中的内容。首次点击外部,应拨打ajax来保存。

编辑:来自以下推荐。

这是新的代码,除了它每次都调用DB之外,它完全有效,我需要的只是在数据不同的情况下进行检查,我想我是从那里得到的。

编辑2:最终代码

    var original_value = '';
    $(".edit_course").focus(function(e) {
        original_value = $(this).html();
    });

    // initialize the "save" function
    $(".edit_course").blur(function(e) {
        var content = $(this).html();
        var id = $(this).data('id');
        var type = $(this).data('type');
        if (content !== original_value) {
            // Ajax edited out
        }
    });

1 个答案:

答案 0 :(得分:1)

您没有正确使用one()。你应该做的是当焦点从div中移开时运行AJAX。使用blur()可能是你最好的选择。

$('body').blur(function(e) {
    // your code here...
});