就地编辑多个输入字段

Edit in-place multiple input fields

我正在构建一个页面,用户可以在其中放置多个带有可就地编辑的输入字段的容器。我现在的脚本允许我在点击时就地编辑输入字段,但我 运行 遇到了 2 个问题:

  1. 我需要单独编辑每个表单。此时单击“编辑”,其他容器中的所有字段也将变为可编辑状态。

  2. 单击取消时,如果键入任何内容,则不应保存任何内容。

See DEMO

JQuery

var readonly = true;
$(".edit").on("click", function(e) {
  $('input[type="text"]').attr("readonly", !readonly);
  readonly = !readonly;
  $(".edit").hide();
  $(".button-group").show();
});
$(".save, .cancel").on("click", function() {
  $(".button-group").hide();
  $(".edit").show();
  $('input[type="text"]').attr("readonly", !readonly);
  readonly = !readonly;
});

谢谢!

您需要从 this 定位父元素的父元素,然后才能正确确定元素的范围。将 .cancel 移动到它自己的侦听器,然后共享代码以关闭 .cancel.save 侦听器的输入。

您也不需要保留 readonly 属性。你可以简单地删除它。请参阅下面的完整示例。

var closeInputs = function(selector, type) {
  var parent = $(selector).parent().parent();
  parent.find(".button-group").hide();
  parent.find(".edit").show();
  // loops through each input
  parent.find('input[type="text"]').each(function() {
    // gets the value from the input if 'save', else get the value of the data-value attribute;
    // default to empty string if either is undefined
    var value = (type === 'save' ? $(this).val() : $(this).attr('data-value')) || '';
    // update this input to readonly, set the data-value attribute with a value, then set the input value
    $(this).attr("readonly", true).attr('data-value', value).val(value);
  });
};
$(".edit").on("click", function(e) {
  var parent = $(this).parent().parent();
  parent.find('input[type="text"]').removeAttr("readonly");
  parent.find(".edit").hide();
  parent.find(".button-group").show();
});
$(".save").on("click", function() {
  closeInputs(this, 'save');
  alert('Going to save.');
});
$(".cancel").on("click", function() {
  closeInputs(this, 'cancel');
  alert('Not going to save.');
});

JS Fiddle: https://codepen.io/anon/pen/zLWLXM