【问题标题】:Reset input-field when click outside the element在元素外部单击时重置输入字段
【发布时间】:2014-05-27 07:48:58
【问题描述】:

我有以下代码可以启用内联编辑

$('.edit_td').click(function() {
    resetEditedCells(); 
    $(this).addClass('active').html('<input type="text" value="' + $(this).html() + '">');
});

function resetEditedCells() {
        $('.edit_td.active').html(function() {
        return $(this).find('input').val();
    });
}

这在从 td 切换到 td 时工作正常。但是当我点击表格外的其他任何地方时,我希望输入字段转换回常规 tds。

我试过这样:

$(document).on('blur', function(e) {
    if($('.edit_td').hasClass('active')) {
        $('.active').remove();
    } else {
        alert("false");
    }

});

.blur() 没有被触发。有人吗?

【问题讨论】:

  • 您知道您正在模糊文档本身吗?不是编辑字段...
  • 也许您正在寻找$(this).removeClass('active').empty().text(original_text);
  • 试试$('input').on('blur'

标签: javascript jquery input reset


【解决方案1】:

尝试这样的方法来替换你的代码

$(document).on('click', function(e) {
    var edit_td = $(e.target).closest('.edit_td');

    if ( edit_td.length > 0 ) {

        resetEditedCells(); 
        edit_td.addClass('active')
               .html('<input type="text" value="' + edit_td.html() + '">');

    }else{

        $('.edit_td.active').removeClass('active').empty();

    }
});

这使用closest() 来确定点击是来自TD 内部还是外部。

【讨论】:

  • 这就是我通常的做法。
【解决方案2】:

你需要使用点击事件而不是模糊:

$(document).click(function() {
 if($('.edit_td').hasClass('active')) {
     $('.active').remove();
 } else {
     alert("false");
}});

还将td点击事件修改为stopPropagation:

$('.edit_td').click(function(e) {
 e.stopPropagation();
 resetEditedCells(); 
 $(this).addClass('active').html('<input type="text" value="' + $(this).html() + '">');
});

【讨论】:

  • 那行不通。当我单击 td 时,会触发对文档的单击,并且 td 不会转换为输入字段。当您第一次单击 td 时,td 应转换为输入字段。当您在表格本身外部单击时,输入字段应重置为 td。
  • 最好在场上直接绑定一个模糊事件。如果你绑定到文档,只要点击网页,就会调用该函数。这会使用不必要的处理能力。
  • @user500468: 你在 td 点击事件中添加了 stopPropagation 吗??
  • @MilindAnantwar:谢谢。但是如何在删除之前捕获输入字段的值呢?编辑:没关系。我解决了:)
  • @MilindAnantwar:删除类后如何恢复 td 及其值?当我在元素外部单击时,td 内的内容被删除。
【解决方案3】:

试试这个 js 代码,其中 edit_td 类应用于每个 td,活动类在活动 td 上,并且模糊函数绑定到应用了“edit_td”和“活动”类的 td。

$('.edit_td.active').on('blur', function(e) {
       $('.active').remove();
    });

【讨论】:

  • 对代码添加一些解释,以便对OP有帮助
  • @CasperSky 解释已添加。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多